since it's a list it cannot be taken directly into range function as the singular integer value of the list is missing.
use this
for i in range(len(myList)):
with this, we get the singular integer value which can be used easily
I'm guessing you get the error on accessing audioSounds
and minTime
, right?
The problem is you can't access instance members
from static methods
. What this means is that, a static method is a method that exists only once and can be used by all other objects (if its access modifier permits it).
Instance members, on the other hand, are created for every instance of the object. So if you create ten instances, how would the runtime know out of all these instances, which audioSounds
list it should access?
Like others said, make your audioSounds
and minTime
static, or you could make your method an instance method, if your design permits it.
You can use
ng-bind-html https://docs.angularjs.org/api/ng/service/$sce
directive to bind html dynamically. However you have to get the data via $sce service.
Please see the live demo at http://plnkr.co/edit/k4s3Bx
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope,$sce) {
$scope.getHtml=function(){
return $sce.trustAsHtml("<b>Hi Rupesh hi <u>dfdfdfdf</u>!</b>sdafsdfsdf<button>dfdfasdf</button>");
}
});
<body ng-controller="MainCtrl">
<span ng-bind-html="getHtml()"></span>
</body>
You have to assign the returned value of the setInterval
function to a variable
var interval;
$(document).on('ready',function(){
interval = setInterval(updateDiv,3000);
});
and then use clearInterval(interval)
to clear it again.
To give the readers another alternative, I am suggesting JACo MP3 Player library, a cross platform java mp3 player.
Features:
For a complete list of its methods and attributes you can check its documentation here.
Sample code:
import jaco.mp3.player.MP3Player;
import java.io.File;
public class Example1 {
public static void main(String[] args) {
new MP3Player(new File("test.mp3")).play();
}
}
For more details, I created a simple tutorial here that includes a downloadable sourcecode.
You can also use sp_who2
which gives more information
Here is some info http://dbadiaries.com/using-sp_who2-to-help-with-sql-server-troubleshooting
You can set tag to fragment in this way:
Fragment fragmentA = new FragmentA();
getFragmentManager().beginTransaction()
.replace(R.id.MainFrameLayout,fragmentA,"YOUR_TARGET_FRAGMENT_TAG")
.addToBackStack("YOUR_SOURCE_FRAGMENT_TAG").commit();
This will have the field take 50% of the width and be centered and resized properly
{ width: 50%; margin-left : 25% }
May also use "vw" (view width) units instead of "%"
I dont know why all these complicated answers are on here but this is what I would do
where pdate >= CURRENT_TIMESTAMP -30
OR WHERE CAST(PDATE AS DATE) >= GETDATE() -30
I don't have enough reputation to comment on any answer. In one of the comments, someone has asked how to ignore the hidden folders in the list. Below is how you can do this.
dir /b /AD-H
char a[2]
defines an array of char
's. a
is a pointer to the memory at the beginning of the array and using ==
won't actually compare the contents of a
with 'ab'
because they aren't actually the same types, 'ab'
is integer type. Also 'ab'
should be "ab"
otherwise you'll have problems here too. To compare arrays of char you'd want to use strcmp.
Something that might be illustrative is looking at the typeid
of 'ab'
:
#include <iostream>
#include <typeinfo>
using namespace std;
int main(){
int some_int =5;
std::cout << typeid('ab').name() << std::endl;
std::cout << typeid(some_int).name() << std::endl;
return 0;
}
on my system this returns:
i
i
showing that 'ab'
is actually evaluated as an int.
If you were to do the same thing with a std::string then you would be dealing with a class and std::string has operator ==
overloaded and will do a comparison check when called this way.
If you wish to compare the input with the string "ab" in an idiomatic c++ way I suggest you do it like so:
#include <iostream>
#include <string>
using namespace std;
int main(){
string a;
cout<<"enter ab ";
cin>>a;
if(a=="ab"){
cout<<"correct";
}
return 0;
}
This one is due to:
if(a=='ab')
, here, a
is const char*
type (ie : array of char)
'ab'
is a constant value,which isn't evaluated as string (because of single quote) but will be evaluated as integer.
Since char
is a primitive type inherited from C, no operator ==
is defined.
the good code should be:
if(strcmp(a,"ab")==0)
, then you'll compare a const char*
to another const char*
using strcmp
.
I have created a utility function (tested once on a device where I was getting an incorrect country code based on locale).
Reference: CountryCodePicker.java
fun getDetectedCountry(context: Context, defaultCountryIsoCode: String): String {
detectSIMCountry(context)?.let {
return it
}
detectNetworkCountry(context)?.let {
return it
}
detectLocaleCountry(context)?.let {
return it
}
return defaultCountryIsoCode
}
private fun detectSIMCountry(context: Context): String? {
try {
val telephonyManager = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
Log.d(TAG, "detectSIMCountry: ${telephonyManager.simCountryIso}")
return telephonyManager.simCountryIso
}
catch (e: Exception) {
e.printStackTrace()
}
return null
}
private fun detectNetworkCountry(context: Context): String? {
try {
val telephonyManager = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
Log.d(TAG, "detectNetworkCountry: ${telephonyManager.simCountryIso}")
return telephonyManager.networkCountryIso
}
catch (e: Exception) {
e.printStackTrace()
}
return null
}
private fun detectLocaleCountry(context: Context): String? {
try {
val localeCountryISO = context.getResources().getConfiguration().locale.getCountry()
Log.d(TAG, "detectNetworkCountry: $localeCountryISO")
return localeCountryISO
}
catch (e: Exception) {
e.printStackTrace()
}
return null
}
You can set a callback function for the onSubmit event of the form and check the contents of each field. If it contains nothing you can then fill it with the string "empty":
<form name="my_form" action="validate.php" onsubmit="check()">
<input type="text" name="text1" />
<input type="submit" value="submit" />
</form>
and in your js:
function check() {
if(document.forms["my_form"]["text1"].value == "")
document.forms["my_form"]["text1"].value = "empty";
}
This prints the number of processes whose basename is "chromium-browser":
ps -e -o args= | awk 'BEGIN{c=0}{
if(!match($1,/^\[.*\]$/)){sub(".*/","",$1)} # Do not strip process names enclosed by square brackets.
if($1==cmd){c++}
}END{print c}' cmd="chromium-browser"
If this prints "0", the process is not running. The command assumes process path does not contain breaking space. I have not tested this with suspended processes or zombie processes.
Tested using gwak
as the awk
alternative in Linux.
Here is a more versatile solution with some example usage:
#!/bin/sh
isProcessRunning() {
if [ "${1-}" = "-q" ]; then
local quiet=1;
shift
else
local quiet=0;
fi
ps -e -o pid,args= | awk 'BEGIN{status=1}{
name=$2
if(name !~ /^\[.*\]$/){sub(".*/","",name)} # strip dirname, if process name is not enclosed by square brackets.
if(name==cmd){status=0; if(q){exit}else{print $0}}
}END{exit status}' cmd="$1" q=$quiet
}
process='chromium-browser'
printf "Process \"${process}\" is "
if isProcessRunning -q "$process"
then printf "running.\n"
else printf "not running.\n"; fi
printf "Listing of matching processes (PID and process name with command line arguments):\n"
isProcessRunning "$process"
I have implement following it working for iOS devices but failed on android devices
<a href="mailto:?subject=Your mate might be interested...&body=<div style='padding: 0;'><div style='padding: 0;'><p>I found this on the site I think you might find it interesting. <a href='@(Request.Url.ToString())' >Click here </a></p></div></div>">Share This</a>
The newly Selected answer submitted by Steven Soroka is close, but not complete. The test itself hides the fact that this is not returning a true 404 - it's returning a status of 200 - "success". The original answer was closer, but attempted to render the layout as if no failure had occurred. This fixes everything:
render :text => 'Not Found', :status => '404'
Here's a typical test set of mine for something I expect to return 404, using RSpec and Shoulda matchers:
describe "user view" do
before do
get :show, :id => 'nonsense'
end
it { should_not assign_to :user }
it { should respond_with :not_found }
it { should respond_with_content_type :html }
it { should_not render_template :show }
it { should_not render_with_layout }
it { should_not set_the_flash }
end
This healthy paranoia allowed me to spot the content-type mismatch when everything else looked peachy :) I check for all these elements: assigned variables, response code, response content type, template rendered, layout rendered, flash messages.
I'll skip the content type check on applications that are strictly html...sometimes. After all, "a skeptic checks ALL the drawers" :)
http://dilbert.com/strips/comic/1998-01-20/
FYI: I don't recommend testing for things that are happening in the controller, ie "should_raise". What you care about is the output. My tests above allowed me to try various solutions, and the tests remain the same whether the solution is raising an exception, special rendering, etc.
When dealing with null, =
does not match the null values. You can use IS NULL
or IS NOT NULL
UPDATE `smartmeter_usage`.`users_reporting`
SET panel_id = 3 WHERE panel_id IS NULL
LIMIT
can be used with UPDATE
but with the row count
only
CREATE PROCEDURE AddBrand
@BrandName nvarchar(50) = null,
@CategoryID int = null
AS
BEGIN
DECLARE @BrandID int = null
SELECT @BrandID = BrandID FROM tblBrand
WHERE BrandName = @BrandName
INSERT INTO tblBrandinCategory (CategoryID, BrandID)
VALUES (@CategoryID, @BrandID)
END
EXEC AddBrand @BrandName = 'BMW', @CategoryId = 1
If you want to return two objects you usually want to return a single object that encapsulates the two objects instead.
You could return a List of NamedObject
objects like this:
public class NamedObject<T> {
public final String name;
public final T object;
public NamedObject(String name, T object) {
this.name = name;
this.object = object;
}
}
Then you can easily return a List<NamedObject<WhateverTypeYouWant>>
.
Also: Why would you want to return a comma-separated list of names instead of a List<String>
? Or better yet, return a Map<String,TheObjectType>
with the keys being the names and the values the objects (unless your objects have specified order, in which case a NavigableMap
might be what you want.
You need to declare your event in the class from myObject :
public event EventHandler<EventArgs> myMethod; //you should name it as an event, like ObjectChanged.
then myNameEvent is the callback to handle the event, and it can be in any other class
I think above examples are correct. but you dont' really need to set
request.setAttribute("selectedDept", selectedDept);
you can reuse that info from JSTL, just do something like this..
<!DOCTYPE html>
<html lang="en">
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<head>
<script src="../js/jquery-1.8.1.min.js"></script>
</head>
<body>
<c:set var="authors" value="aaa,bbb,ccc,ddd,eee,fff,ggg" scope="application" />
<c:out value="Before : ${param.Author}"/>
<form action="TestSelect.action">
<label>Author
<select id="Author" name="Author">
<c:forEach items="${fn:split(authors, ',')}" var="author">
<option value="${author}" ${author == param.Author ? 'selected' : ''}>${author}</option>
</c:forEach>
</select>
</label>
<button type="submit" value="submit" name="Submit"></button>
<Br>
<c:out value="After : ${param.Author}"/>
</form>
</body>
</html>
In SWIFT 3.0
if let url = URL(string: "https://www.google.com") {
UIApplication.shared.open(url, options: [:])
}
You must add this code in your Service class so that it handles the case when your process is being killed
@Override
public void onTaskRemoved(Intent rootIntent) {
Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
restartServiceIntent.setPackage(getPackageName());
PendingIntent restartServicePendingIntent = PendingIntent.getService(getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmService.set(
AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + 1000,
restartServicePendingIntent);
super.onTaskRemoved(rootIntent);
}
I found this resource that details the various methods: How to embed TIFF files in HTML documents
As mentioned, it will very much depend on browser support for the format. Viewing that page in Chrome on Windows didn't display any of the images.
It would also be helpful if you posted the code you've tried already.
You can have a look to XxHash.Net ( https://github.com/wilhelmliao/xxHash.NET )
The xxHash algorythm seems to be faster than all other.
Some benchmark on the xxHash site : https://github.com/Cyan4973/xxHash
PS: I've not yet used it.
Here is another idea for you. It is also online w/ no download. It uses window 7 + ie9 with no flash support though ie9 online
Ignore is exactly what the name implies.
It doesn't "throw away" something you don't need instead, it ignores the amount of characters you specify when you call it, up to the char you specify as a breakpoint.
It works with both input and output buffers.
Essentially, for std::cin
statements you use ignore before you do a getline
call, because when a user inputs something with std::cin
, they hit enter and a '\n'
char gets into the cin
buffer. Then if you use getline
, it gets the newline char instead of the string you want. So you do a std::cin.ignore(1000,'\n')
and that should clear the buffer up to the string that you want. (The 1000 is put there to skip over a specific amount of chars before the specified break point, in this case, the \n newline character.)
A modified python version of @danack's PHP generate script. It generates all files & folders that live inside of build/
to the parent directory, replacing all {{placeholder}}
matches. You need to cd
into build/
before running the script.
File structure
build/
-- (files/folders you want to generate)
-- build.py
sites-available/...
sites-enabled/...
nginx.conf
...
build.py
import os, re
# Configurations
target = os.path.join('.', '..')
variables = {
'placeholder': 'your replacement here'
}
# Loop files
def loop(cb, subdir=''):
dir = os.path.join('.', subdir);
for name in os.listdir(dir):
file = os.path.join(dir, name)
newsubdir = os.path.join(subdir, name)
if name == 'build.py': continue
if os.path.isdir(file): loop(cb, newsubdir)
else: cb(subdir, name)
# Update file
def replacer(subdir, name):
dir = os.path.join(target, subdir)
file = os.path.join(dir, name)
oldfile = os.path.join('.', subdir, name)
with open(oldfile, "r") as fin:
data = fin.read()
for key, replacement in variables.iteritems():
data = re.sub(r"{{\s*" + key + "\s*}}", replacement, data)
if not os.path.exists(dir):
os.makedirs(dir)
with open(file, "w") as fout:
fout.write(data)
# Start variable replacements.
loop(replacer)
Position your <div>
absolutely at the bottom and don't forget to give div.A
a position: relative
- http://jsfiddle.net/TTaMx/
.A {
position: relative;
margin: 40px 0;
height: 40px;
width: 200px;
background: #eee;
}
.A:after {
content: " ";
display: block;
background: #c00;
height: 29px;
width: 100%;
position: absolute;
bottom: -29px;
}?
I decided to hide the badge on all pages except my contact page (using Wordpress):
/* Hides the reCAPTCHA on every page */
.grecaptcha-badge {
visibility: hidden !important;
}
/* Shows the reCAPTCHA on the Contact page */
/* Obviously change the page number to your own */
.page-id-17 .grecaptcha-badge {
visibility: visible !important;
}
I'm not a web developer so please correct me if there's something wrong.
EDIT: Updated to use visibility instead of display.
BinaryReader b = new BinaryReader(file.InputStream);
byte[] binData = b.ReadBytes(file.InputStream.Length);
line 2 should be replaced with
byte[] binData = b.ReadBytes(file.ContentLength);
when it comes to subquery and co-related query both have inner query and outer query the only difference is in subquery the inner query doesn't depend on outer query, whereas in co-related inner query depends on outer.
Generics
can be defined using Wrapper
classes only. If you don't want to define using Wrapper types, you may use the Raw definition as below
@SuppressWarnings("rawtypes")
public HashMap buildMap(String letters)
{
HashMap checkSum = new HashMap();
for ( int i = 0; i < letters.length(); ++i )
{
checkSum.put(letters.charAt(i), primes[i]);
}
return checkSum;
}
Or define the HashMap using wrapper types, and store the primitive types. The primitive values will be promoted to their wrapper types.
public HashMap<Character, Integer> buildMap(String letters)
{
HashMap<Character, Integer> checkSum = new HashMap<Character, Integer>();
for ( int i = 0; i < letters.length(); ++i )
{
checkSum.put(letters.charAt(i), primes[i]);
}
return checkSum;
}
The whole concept of inversion of control means you are free from a chore to instantiate objects manually and provide all necessary dependencies.
When you annotate class with appropriate annotation (e.g. @Service
) Spring will automatically instantiate object for you. If you are not familiar with annotations you can also use XML file instead. However, it's not a bad idea to instantiate classes manually (with the new
keyword) in unit tests when you don't want to load the whole spring context.
if(window.location.href.indexOf("?added-to-cart=555") >= 0)
It's window.location.href
, not window.location
.
The AngularJS documentation on directives is pretty well written for what the symbols mean.
To be clear, you cannot just have
scope: '@'
in a directive definition. You must have properties for which those bindings apply, as in:
scope: {
myProperty: '@'
}
I strongly suggest you read the documentation and the tutorials on the site. There is much more information you need to know about isolated scopes and other topics.
Here is a direct quote from the above-linked page, regarding the values of scope
:
The scope property can be true, an object or a falsy value:
falsy: No scope will be created for the directive. The directive will use its parent's scope.
true
: A new child scope that prototypically inherits from its parent will be created for the directive's element. If multiple directives on the same element request a new scope, only one new scope is created. The new scope rule does not apply for the root of the template since the root of the template always gets a new scope.
{...}
(an object hash): A new "isolate" scope is created for the directive's element. The 'isolate' scope differs from normal scope in that it does not prototypically inherit from its parent scope. This is useful when creating reusable components, which should not accidentally read or modify data in the parent scope.
Retrieved 2017-02-13 from https://code.angularjs.org/1.4.11/docs/api/ng/service/$compile#-scope-, licensed as CC-by-SA 3.0
I had to add packaging, so:
mvn install:install-file \
-DgroupId=javax.transaction \
-DartifactId=jta \
-Dversion=1.0.1B \
-Dfile=jta-1.0.1B.jar \
-DgeneratePom=true \
-Dpackaging=jar
If you are using HTML5 date
use this code
HTML
<input type="date" name="bday" id="start_date"/>
Java Script
document.getElementById('start_date').value = Date();
A simple semantic name would be last
. This would allow code always positive code like:
if (item.last)
...
do {
...
} until (item.last);
In Angular 2 [email protected],
To run a new project on the different port, one way is to specify the port while you run ng serve command.
ng serve --port 4201
or the other way, you can edit your package.json file scripts part and attached the port to your start variable like I mentioned below and then simply run "npm start"
"scripts": {
"ng": "ng",
"start": "ng serve --port 4201",
... : ...,
... : ....
}
this way is much better where you don't need to define port explicitly every time.
Try this
$data1 = strtotime(\date("d/m/Y"));
$data1 = date_create($data1);
$data2 = date_create("21/06/2017");
if($data1 < $data2){
return "The most current date is date1";
}
return "The most current date is date2";
Xcode 8.X , Swift 3.X
Easy Use;
let params:NSMutableDictionary? = ["foo": "bar"];
let ulr = NSURL(string:"http://mywebsite.com/post-request" as String)
let request = NSMutableURLRequest(url: ulr! as URL)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let data = try! JSONSerialization.data(withJSONObject: params!, options: JSONSerialization.WritingOptions.prettyPrinted)
let json = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
if let json = json {
print(json)
}
request.httpBody = json!.data(using: String.Encoding.utf8.rawValue);
Alamofire.request(request as! URLRequestConvertible)
.responseJSON { response in
// do whatever you want here
print(response.request)
print(response.response)
print(response.data)
print(response.result)
}
This works for deleting all the directories and files within a directory.
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
int main()
{
cout << "Enter the DirectoryName to Delete : ";
string directoryName;
cin >> directoryName;
string a = "rmdir /s /q " + directoryName;
system(a.c_str());
return 0;
}
I Know this is a old question, and Pawel has given the correct answer, I just wanted to show a code example of how to do some string processing, and avoid an extra class for the list of a primitive type.
public class Test
{
public Test()
{
_strings = new List<string>
{
"test",
"test2",
"test3",
"test4"
};
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
private List<String> _strings { get; set; }
public List<string> Strings
{
get { return _strings; }
set { _strings = value; }
}
[Required]
public string StringsAsString
{
get { return String.Join(',', _strings); }
set { _strings = value.Split(',').ToList(); }
}
}
There are following different ways to perform 360 degree animation with UIView.
Using CABasicAnimation
var rotationAnimation = CABasicAnimation()
rotationAnimation = CABasicAnimation.init(keyPath: "transform.rotation.z")
rotationAnimation.toValue = NSNumber(value: (Double.pi))
rotationAnimation.duration = 1.0
rotationAnimation.isCumulative = true
rotationAnimation.repeatCount = 100.0
view.layer.add(rotationAnimation, forKey: "rotationAnimation")
Here is an extension functions for UIView that handles start & stop rotation operations:
extension UIView {
// Start rotation
func startRotation() {
let rotation = CABasicAnimation(keyPath: "transform.rotation.z")
rotation.fromValue = 0
rotation.toValue = NSNumber(value: Double.pi)
rotation.duration = 1.0
rotation.isCumulative = true
rotation.repeatCount = FLT_MAX
self.layer.add(rotation, forKey: "rotationAnimation")
}
// Stop rotation
func stopRotation() {
self.layer.removeAnimation(forKey: "rotationAnimation")
}
}
Now using, UIView.animation closure:
UIView.animate(withDuration: 0.5, animations: {
view.transform = CGAffineTransform(rotationAngle: (CGFloat(Double.pi))
}) { (isAnimationComplete) in
// Animation completed
}
HashMap
is unordered per the second line of the documentation:
This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.
Perhaps you can do as aix suggests and use a LinkedHashMap
, or another ordered collection. This link can help you find the most appropriate collection to use.
Here's another solution: http://jsfiddle.net/6WvUY/7/.
HTML:
<div class="container">
<div class="row">
<div class="col-sm-6">
<img src="//placehold.it/600x300" alt="Logo" class="img-responsive"/>
</div>
<div class="col-sm-6">
<h3>Some Text</h3>
</div>
</div>
</div>
CSS:
.row {
display: table;
}
.row > div {
float: none;
display: table-cell;
}
Instead of using HTML comments (which have no effect on PHP code -- which will still be executed), you should use PHP comments:
<?php /*
<tr>
<td><?php echo $entry_keyword; ?></td>
<td><input type="text" name="keyword" value="<?php echo $keyword; ?>" /></td>
</tr>
<tr>
<td><?php echo $entry_sort_order; ?></td>
<td><input name="sort_order" value="<?php echo $sort_order; ?>" size="1" /></td>
</tr>
*/ ?>
With that, the PHP code inside the HTML will not be executed; and nothing (not the HTML, not the PHP, not the result of its non-execution) will be displayed.
Just one note: you cannot nest C-style comments... which means the comment will end at the first */
encountered.
You can escape the calc
arguments in order to prevent them from being evaluated on compilation.
Using your example, you would simply surround the arguments, like this:
calc(~'100% - 10px')
Demo : http://jsfiddle.net/c5aq20b6/
I find that I use this in one of the following three ways:
Everything inside the calc
arguments is defined as a string, and is totally static until it's evaluated by the client:
div {
> span {
width: calc(~'100% - 10px');
}
}
div > span {
width: calc(100% - 10px);
}
You can insert a LESS variable into the string:
div {
> span {
@pad: 10px;
width: calc(~'100% - @{pad}');
}
}
div > span {
width: calc(100% - 10px);
}
You may want to escape a percentage value, but go ahead and evaluate something on compilation:
@btnWidth: 40px;
div {
> span {
@pad: 10px;
width: calc(~'(100% - @{pad})' - (@btnWidth * 2));
}
}
div > span {
width: calc((100% - 10px) - 80px);
}
Source: http://lesscss.org/functions/#string-functions-escape.
At the beginning of your main method, add this line of code :
final long startTime = System.nanoTime();
And then, at the last line of your main method, you can add :
final long duration = System.nanoTime() - startTime;
duration
now contains the time in nanoseconds that your program ran. You can for example print this value like this:
System.out.println(duration);
If you want to show duration time in seconds, you must divide the value by 1'000'000'000. Or if you want a Date
object: Date myTime = new Date(duration / 1000);
You can then access the various methods of Date
to print number of minutes, hours, etc.
Use sudo pip install scipy
to install the library so It cannot ask for permissions later
If you are not allowed to use C++'s string class (which is terrible teaching C++ imho), a raw, safe array version would look something like this.
#include <cstring>
#include <iostream>
int main()
{
char array1[] ="The dog jumps ";
char array2[] = "over the log";
char * newArray = new char[std::strlen(array1)+std::strlen(array2)+1];
std::strcpy(newArray,array1);
std::strcat(newArray,array2);
std::cout << newArray << std::endl;
delete [] newArray;
return 0;
}
This assures you have enough space in the array you're doing the concatenation to, without assuming some predefined MAX_SIZE
. The only requirement is that your strings are null-terminated, which is usually the case unless you're doing some weird fixed-size string hacking.
Edit, a safe version with the "enough buffer space" assumption:
#include <cstring>
#include <iostream>
int main()
{
const unsigned BUFFER_SIZE = 50;
char array1[BUFFER_SIZE];
std::strncpy(array1, "The dog jumps ", BUFFER_SIZE-1); //-1 for null-termination
char array2[] = "over the log";
std::strncat(array1,array2,BUFFER_SIZE-strlen(array1)-1); //-1 for null-termination
std::cout << array1 << std::endl;
return 0;
}
So to make your expression work, changing &&
for -a
will do the trick.
It is correct like this:
if [ -f $VAR1 ] && [ -f $VAR2 ] && [ -f $VAR3 ]
then ....
or like
if [[ -f $VAR1 && -f $VAR2 && -f $VAR3 ]]
then ....
or even
if [ -f $VAR1 -a -f $VAR2 -a -f $VAR3 ]
then ....
You can find further details in this question bash : Multiple Unary operators in if statement and some references given there like What is the difference between test, [ and [[ ?.
You can use <LinearLayout>
to group elements horizontaly. Also you should use style to set margins, background and other properties. This will allow you not to repeat code for every label you use.
Here is an example:
<LinearLayout
style="@style/FormItem"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
style="@style/FormLabel"
android:layout_width="wrap_content"
android:layout_height="@dimen/default_element_height"
android:text="@string/name_label"
/>
<EditText
style="@style/FormText.Editable"
android:id="@+id/cardholderName"
android:layout_width="wrap_content"
android:layout_height="@dimen/default_element_height"
android:layout_weight="1"
android:gravity="right|center_vertical"
android:hint="@string/card_name_hint"
android:imeOptions="actionNext"
android:singleLine="true"
/>
</LinearLayout>
Also you can create a custom view base on the layout above. Have you looked at Creating custom view ?
You need to move your angular app code below the inclusion of the angular libraries. At the time your angular code runs, angular
does not exist yet. This is an error (see your dev tools console).
In this line:
var app = angular.module(`
you are attempting to access a variable called angular
. Consider what causes that variable to exist. That is found in the angular.js script which must then be included first.
<h1>{{2+3}}</h1>
<!-- In production use:
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
-->
<script src="lib/angular/angular.js"></script>
<script src="lib/angular/angular-route.js"></script>
<script src="js/app.js"></script>
<script src="js/services.js"></script>
<script src="js/controllers.js"></script>
<script src="js/filters.js"></script>
<script src="js/directives.js"></script>
<script>
var app = angular.module('myApp',[]);
app.directive('myDirective',function(){
return function(scope, element,attrs) {
element.bind('click',function() {alert('click')});
};
});
</script>
For completeness, it is true that your directive is similar to the already existing directive ng-click
, but I believe the point of this exercise is just to practice writing simple directives, so that makes sense.
double totalMinutes = (end-start).TotalMinutes;
Try this
SELECT *
FROM categories
LEFT JOIN user_category_subscriptions
ON user_category_subscriptions.category_id = categories.category_id
WHERE user_category_subscriptions.user_id = 1
or user_category_subscriptions.user_id is null
Just add Axios.defaults.withCredentials=true
instead of ({credentials: true}
) in client side,
and change app.use(cors())
to
app.use(cors(
{origin: ['your client side server'],
methods: ['GET', 'POST'],
credentials:true,
}
))
Though this is an old question and asked several times, here's what I'm doing after hours fidgeting with here
strings, and the only option that worked for me is to store the value in a file during while loop sub-shells and then retrieve it. Simple.
Use echo
statement to store and cat
statement to retrieve. And the bash user must chown
the directory or have read-write chmod
access.
#write to file
echo "1" > foo.txt
while condition; do
if (condition); then
#write again to file
echo "2" > foo.txt
fi
done
#read from file
echo "Value of \$foo in while loop body: $(cat foo.txt)"
Figuring out dependencies for small projects is not hard. But once you start dealing with a dependency tree with hundreds of dependencies, things can easily get out of hand. (I'm speaking from experience here ...)
The other point is that if you use an IDE with incremental compilation and Maven support (like Eclipse + m2eclipse), then you should be able to set up edit/compile/hot deploy and test.
I personally don't do this because I've come to distrust this mode of development due to bad experiences in the past (pre Maven). Perhaps someone can comment on whether this actually works with Eclipse + m2eclipse.
With Git there is no “correct” workflow. Use whatever floats your boat. However, if you constantly get conflicts when merging branches maybe you should coordinate your efforts better with your fellow developer(s)? Sounds like the two of you keep editing the same files. Also, watch out for whitespace and subversion keywords (i.e., “$Id$” and others).
I am telling a simple Technic which I follow
SP_HELP 'table_name'
run this code as query. Mention your table name at place of table_name for which you want to know Primary Key (don't forget the single quotes). The result will show like attached Image. Hope it will help you
IMHO I disagree with RickNotFred's statement:
Popping a dialog when an EditText gets focus seems like a non-standard interface.
Displaying a dialog to edit the date when the use presses the an EditText is very similar to the default, which is to display a keyboard or a numeric key pad. The fact that the date is displayed with the EditText signals to the user that the date may be changed. Displaying the date as a non-editable TextView signals to the user that the date may not be changed.
One module that I have been using for this exact use case is require-all.
It recursively requires all files in a given directory and its sub directories as long they don't match the excludeDirs
property.
It also allows specifying a file filter and how to derive the keys of the returned hash from the filenames.
I was trying to also sort by a DateTime field descending and this seems to do the trick:
var ud = (from d in env
orderby -d.ReportDate.Ticks
select d.ReportDate.ToString("yyyy-MMM") ).Distinct();
to make your code look better when viewing source
$variable = 'foo';
echo "this is my php variable $variable \n";
echo "this is another php echo here $variable\n";
your code when view source will look like, with nice line returns thanks to \n
this is my php variable foo
this is another php echo here foo
If you build with the lastest beta iOS 13.4 and XCode 11.4, the accepted answer won't work anymore. I've found another way, maybe it's just a bug in the beta software, but I'm writing it down there, just in case
(swift 5)
import UIKit
class TransparentNavBar :UINavigationBar {
override func awakeFromNib() {
super.awakeFromNib()
self.setBackgroundImage(UIImage(), for: .default)
self.shadowImage = UIImage()
self.isTranslucent = true
self.backgroundColor = .clear
if #available(iOS 13.0, *) {
self.standardAppearance.backgroundColor = .clear
self.standardAppearance.backgroundEffect = .none
self.standardAppearance.shadowColor = .clear
}
}
}
you CAN give it environment variables. Just preppend env: before the variable name, like this:
value="${env:MY_HOME}/logs/message.log"
Converting a range to a table as described in this answer:
Sub CreateTable() ActiveSheet.ListObjects.Add(xlSrcRange, Range("$B$1:$D$16"), , xlYes).Name = _ "Table1" 'No go in 2003 ActiveSheet.ListObjects("Table1").TableStyle = "TableStyleLight2" End Sub
In case anyone else is stuck with this: it just means the write permissions are wrong in the repo that you’re pushing to. Go and chmod -R it so that the user you’re accessing the git server with has write access.
http://blog.shamess.info/2011/05/06/remote-rejected-na-unpacker-error/
It just works.
SSMS only allows unlimited data for XML data. This is not the default and needs to be set in the options.
One trick which might work in quite limited circumstances is simply naming the column in a special manner as below so it gets treated as XML data.
DECLARE @S varchar(max) = 'A'
SET @S = REPLICATE(@S,100000) + 'B'
SELECT @S as [XML_F52E2B61-18A1-11d1-B105-00805F49916B]
In SSMS (at least versions 2012 to current of 18.3) this displays the results as below
Clicking on it opens the full results in the XML viewer. Scrolling to the right shows the last character of B is preserved,
However this does have some significant problems. Adding extra columns to the query breaks the effect and extra rows all become concatenated with the first one. Finally if the string contains characters such as <
opening the XML viewer fails with a parsing error.
A more robust way of doing this that avoids issues of SQL Server converting <
to <
etc or failing due to these characters is below (credit Adam Machanic here).
DECLARE @S varchar(max)
SELECT @S = ''
SELECT @S = @S + '
' + OBJECT_DEFINITION(OBJECT_ID) FROM SYS.PROCEDURES
SELECT @S AS [processing-instruction(x)] FOR XML PATH('')
You can read more about function types in the language specification in sections 3.5.3.5 and 3.5.5.
The TypeScript compiler will infer types when it can, and this is done you do not need to specify explicit types. so for the greeter example, greet() returns a string literal, which tells the compiler that the type of the function is a string, and no need to specify a type. so for instance in this sample, I have the greeter class with a greet method that returns a string, and a variable that is assigned to number literal. the compiler will infer both types and you will get an error if you try to assign a string to a number.
class Greeter {
greet() {
return "Hello, "; // type infered to be string
}
}
var x = 0; // type infered to be number
// now if you try to do this, you will get an error for incompatable types
x = new Greeter().greet();
Similarly, this sample will cause an error as the compiler, given the information, has no way to decide the type, and this will be a place where you have to have an explicit return type.
function foo(){
if (true)
return "string";
else
return 0;
}
This, however, will work:
function foo() : any{
if (true)
return "string";
else
return 0;
}
When FIND
returns #VALUE!
, it is an error, not a string, so you can't compare FIND(...)
with "#VALUE!"
, you need to check if FIND
returns an error with ISERROR
. Also FIND
can work on multiple characters.
So a simplified and working version of your formula would be:
=IF(ISERROR(FIND("abc",A1))=FALSE, "Green", IF(ISERROR(FIND("xyz",A1))=FALSE, "Yellow", "Red"))
Or, to remove the double negations:
=IF(ISERROR(FIND("abc",A1)), IF(ISERROR(FIND("xyz",A1)), "Red", "Yellow"),"Green")
Perhaps you don't have to include the single quotes:
curl --request POST 'http://localhost/Service' --data "path=/xyz/pqr/test/&fileName=1.doc"
Update: Reading curl's manual, you could actually separate both fields with two --data:
curl --request POST 'http://localhost/Service' --data "path=/xyz/pqr/test/" --data "fileName=1.doc"
You could also try --data-binary:
curl --request POST 'http://localhost/Service' --data-binary "path=/xyz/pqr/test/" --data-binary "fileName=1.doc"
And --data-urlencode:
curl --request POST 'http://localhost/Service' --data-urlencode "path=/xyz/pqr/test/" --data-urlencode "fileName=1.doc"
Below is a simple way of accessing the response as a String using Apache HTTP Client library.
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
//...
HttpGet get;
HttpClient httpClient;
// initialize variables above
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpClient.execute(get, responseHandler);
The best way to secure phpMyAdmin is the combination of all these 4:
1. Change phpMyAdmin URL
2. Restrict access to localhost only.
3. Connect through SSH and tunnel connection to a local port on your computer
4. Setup SSL to already encrypted SSH connection. (x2 security)
Here is how to do these all with: Ubuntu 16.4 + Apache 2 Setup Windows computer + PuTTY to connect and tunnel the SSH connection to a local port:
# Secure Web Serving of phpMyAdmin (change URL of phpMyAdmin):
sudo nano /etc/apache2/conf-available/phpmyadmin.conf
/etc/phpmyadmin/apache.conf
Change: phpmyadmin URL by this line:
Alias /newphpmyadminname /usr/share/phpmyadmin
Add: AllowOverride All
<Directory /usr/share/phpmyadmin>
Options FollowSymLinks
DirectoryIndex index.php
AllowOverride Limit
...
sudo systemctl restart apache2
sudo nano /usr/share/phpmyadmin/.htaccess
deny from all
allow from 127.0.0.1
alias phpmyadmin="sudo nano /usr/share/phpmyadmin/.htaccess"
alias myip="echo ${SSH_CONNECTION%% *}"
# Secure Web Access to phpMyAdmin:
Make sure pma.yourdomain.com is added to Let's Encrypt SSL configuration:
https://www.digitalocean.com/community/tutorials/how-to-secure-apache-with-let-s-encrypt-on-ubuntu-16-04
PuTTY => Source Port (local): <local_free_port> - Destination: 127.0.0.1:443 (OR localhost:443) - Local, Auto - Add
C:\Windows\System32\drivers\etc
Notepad - Run As Administrator - open: hosts
127.0.0.1 pma.yourdomain.com
https://pma.yourdomain.com:<local_free_port>/newphpmyadminname/ (HTTPS OK, SSL VPN OK)
https://localhost:<local_free_port>/newphpmyadminname/ (HTTPS ERROR, SSL VPN OK)
# Check to make sure you are on SSH Tunnel
1. Windows - CMD:
ping pma.yourdomain.com
ping www.yourdomain.com
# See PuTTY ports:
netstat -ano |find /i "listening"
2. Test live:
https://pma.yourdomain.com:<local_free_port>/newphpmyadminname/
If you are able to do these all successfully,
you now have your own url path for phpmyadmin,
you denied all access to phpmyadmin except localhost,
you connected to your server with SSH,
you tunneled that connection to a port locally,
you connected to phpmyadmin as if you are on your server,
you have additional SSL conenction (HTTPS) to phpmyadmin in case something leaks or breaks.
I often use this snippet for simple scripts:
#!/bin/bash
if [ -z "$1" ]; then
echo -e "\nPlease call '$0 <argument>' to run this command!\n"
exit 1
fi
To get Correct Week Count for Date 2018-12-31 Please use below Code
$day_count = date('N',strtotime('2018-12-31'));
$week_count = date('W',strtotime('2018-12-31'));
if($week_count=='01' && date('m',strtotime('2018-12-31'))==12){
$yr_count = date('y',strtotime('2018-12-31')) + 1;
}else{
$yr_count = date('y',strtotime('2018-12-31'));
}
If you are using Linux you can use the wget
module of Linux through the python shell. Here is a sample code snippet
import os
url = 'http://www.example.com/foo.zip'
os.system('wget %s'%url)
Use the reset function, which is available on the form element.
var form = document.getElementById("myForm");
form.reset();
Use a parameterized query to prevent Sql injections (secutity problem)
Use the using statement so the connection will be closed and resources will be disposed.
using(var connection = new SqlConnection("connectionString"))
{
connection.Open();
var sql = "INSERT INTO Main(FirstName, SecondName) VALUES(@FirstName, @SecondName)";
using(var cmd = new SqlCommand(sql, connection))
{
cmd.Parameters.AddWithValue("@FirstName", txFirstName.Text);
cmd.Parameters.AddWithValue("@SecondName", txSecondName.Text);
cmd.ExecuteNonQuery();
}
}
I'm going to piggyback a bit on @frankodwyer's great answer and dig a little deeper into online-based licensing. I'm the founder of Keygen, a licensing REST API built for developers.
Since you mentioned wanting 2 "types" of licenses for your application, i.e. a "full version" and a "trial version", we can simplify that and use a feature license model where you license specific features of your application (in this case, there's a "full" feature-set and a "trial" feature-set).
To start off, we could create 2 license types (called policies in Keygen) and whenever a user registers an account you can generate a "trial" license for them to start out (the "trial" license implements our "trial" feature policy), which you can use to do various checks within the app e.g. can user use Trial-Feature-A and Trial-Feature-B.
And building on that, whenever a user purchases your app (whether you're using PayPal, Stripe, etc.), you can generate a license implementing the "full" feature policy and associate it with the user's account. Now within your app you can check if the user has a "full" license that can do Pro-Feature-X and Pro-Feature-Y (by doing something like user.HasLicenseFor(FEATURE_POLICY_ID)
).
I mentioned allowing your users to create user accounts—what do I mean by that? I've gone into this in detail in a couple other answers, but a quick rundown as to why I think this is a superior way to authenticate and identify your users:
Of course, if you don't want to handle user accounts and you want your users to input license keys, that's completely fine (and Keygen supports doing that as well). I'm just offering another way to go about handling that aspect of licensing and hopefully provide a nice UX for your customers.
Finally since you also mentioned that you want to update these licenses annually, you can set a duration on your policies so that "full" licenses will expire after a year and "trial" licenses last say 2 weeks, requiring that your users purchase a new license after expiration.
I could dig in more, getting into associating machines with users and things like that, but I thought I'd try to keep this answer short and focus on simply licensing features to your users.
mylist[c(5,7,9)]
should do it.
You want the sublists returned as sublists of the result list; you don't use [[]]
(or rather, the function is [[
) for that -- as Dason mentions in comments, [[
grabs the element.
It happens because the view needs more time to be inflated. So instead of calling view.width
and view.height
on the main thread, you should use view.post { ... }
to make sure that your view
has already been inflated. In Kotlin:
view.post{width}
view.post{height}
In Java you can also call getWidth()
and getHeight()
methods in a Runnable
and pass the Runnable
to view.post()
method.
view.post(new Runnable() {
@Override
public void run() {
view.getWidth();
view.getHeight();
}
});
@balusC I did as you wrote . In my case , I've added cookie information to be able to reuse the session .
// get the cookie if need
String cookies = conn.getHeaderField("Set-Cookie");
// open the new connnection again
conn = (HttpURLConnection) new URL(newUrl).openConnection();
conn.setRequestProperty("Cookie", cookies);
In CMD, type:
pip freeze
And it will show you a list of all the modules installed including the version number.
Output:
aiohttp==1.1.4
async-timeout==1.1.0
cx-Freeze==4.3.4
Django==1.9.2
django-allauth==0.24.1
django-cors-headers==1.2.2
django-crispy-forms==1.6.0
django-robots==2.0
djangorestframework==3.3.2
easygui==0.98.0
future==0.16.0
httpie==0.9.6
matplotlib==1.5.3
multidict==2.1.2
numpy==1.11.2
oauthlib==1.0.3
pandas==0.19.1
pefile==2016.3.28
pygame==1.9.2b1
Pygments==2.1.3
PyInstaller==3.2
pyparsing==2.1.10
pypiwin32==219
PyQt5==5.7
pytz==2016.7
requests==2.9.1
requests-oauthlib==0.6
six==1.10.0
sympy==1.0
virtualenv==15.0.3
xlrd==1.0.0
yarl==0.7.0
Solved it by removing the "Excluded" in the module setting (right click on project, "Open module settings").
Here is an unbiased version that generates numbers in [low, high]
:
int r;
do {
r = rand();
} while (r < ((unsigned int)(RAND_MAX) + 1) % (high + 1 - low));
return r % (high + 1 - low) + low;
If your range is reasonably small, there is no reason to cache the right-hand side of the comparison in the do
loop.
There is an option without additional packages that works under pdflatex
Adapt this code
\begin{figure}[h]
\centering
\includegraphics[width=\ScaleIfNeeded]{figuras/diagrama-spearman.pdf}
\caption{Schematical view of Spearman's theory.}
\end{figure}
"diagrama-spearman.pdf" is a plot generated with TikZ and this is the code (it is another .tex file different from the .tex file where I want to insert a pdf)
\documentclass[border=3mm]{standalone}
\usepackage[applemac]{inputenc}
\usepackage[protrusion=true,expansion=true]{microtype}
\usepackage[bb=lucida,bbscaled=1,cal=boondoxo]{mathalfa}
\usepackage[stdmathitalics=true,math-style=iso,lucidasmallscale=true,romanfamily=bright]{lucimatx}
\usepackage{tikz}
\usetikzlibrary{intersections}
\newcommand{\at}{\makeatletter @\makeatother}
\begin{document}
\begin{tikzpicture}
\tikzset{venn circle/.style={draw,circle,minimum width=5cm,fill=#1,opacity=1}}
\node [venn circle = none, name path=A] (A) at (45:2cm) { };
\node [venn circle = none, name path=B] (B) at (135:2cm) { };
\node [venn circle = none, name path=C] (C) at (225:2cm) { };
\node [venn circle = none, name path=D] (D) at (315:2cm) { };
\node[above right] at (barycentric cs:A=1) {logical};
\node[above left] at (barycentric cs:B=1) {mechanical};
\node[below left] at (barycentric cs:C=1) {spatial};
\node[below right] at (barycentric cs:D=1) {arithmetical};
\node at (0,0) {G};
\end{tikzpicture}
\end{document}
This is the diagram I included
This is done using the REPLACE function
To strip out "somestring" from "SomeColumn" in "SomeTable" in the SELECT query:
SELECT REPLACE([SomeColumn],'somestring','') AS [SomeColumn] FROM [SomeTable]
To update the table and strip out "somestring" from "SomeColumn" in "SomeTable"
UPDATE [SomeTable] SET [SomeColumn] = REPLACE([SomeColumn], 'somestring', '')
try setting both html
and body
to height 100%;
html, body {background: blue; height:100%;}
well, as an easier alternative and shorter, you could do this too!!
var fd = new FormData();
var file_data = object.get(0).files[i];
var other_data = $('form').serialize(); //page_id=&category_id=15&method=upload&required%5Bcategory_id%5D=Category+ID
fd.append("file", file_data);
$.ajax({
url: 'add.php?'+ other_data, //<== just add it to the end of url ***
data: fd,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
}
});
It happened in IE 11 for me. And I was calling the jquery .load function. So I did it the old fashion way and put something in the url to disable cacheing.
$("#divToReplaceHtml").load('@Url.Action("Action", "Controller")/' + @Model.ID + "?nocache=" + new Date().getTime());
The answer probably depends on what format your date is in, but here is an example using the Date
class:
dt <- as.Date("2010/02/10")
new.dt <- dt - as.difftime(2, unit="days")
You can even play with different units like weeks.
String[] result = "hi i'm paul".split("\\s+");
to split across one or more cases.
Or you could take a look at Apache Common StringUtils. It has StringUtils.split(String str)
method that splits string using white space as delimiter. It also has other useful utility methods
SQLite also supports a pragma statement called "table_info" which returns one row per column in a table with the name of the column (and other information about the column). You could use this in a query to check for the missing column, and if not present alter the table.
PRAGMA table_info(foo_table_name)
Try this:
class mystuff:
def average(_,a,b,c): #get the average of three numbers
result=a+b+c
result=result/3
return result
#now use the function average from the mystuff class
print mystuff.average(9,18,27)
or this:
class mystuff:
def average(self,a,b,c): #get the average of three numbers
result=a+b+c
result=result/3
return result
#now use the function average from the mystuff class
print mystuff.average(9,18,27)
You need to use the scrollTop
property.
document.getElementById('box').scrollTop
You could just redirect them to another page. Actually making it literally click a link and travel to it seems unnessacary, but I don't know the whole story.
The pipe character |
has a special meaning in regular expressions. a|b
means "match either a
or b
". If you want to match a literal |
character, you need to escape it:
... | Select-String -Pattern 'H\|159' -NotMatch | ...
I think a lot of folks are looking for a footer on the bottom that scrolls instead of being fixed, called a sticky footer. Fixed footers will cover body content when the height is too short. You have to set the html, body, and page container to a height of 100%, set your footer to absolute position bottom. Your page content container needs a relative position for this to work. Your footer has a negative margin equal to height of footer minus bottom margin of page content. See the example page I posted.
Example with notes: http://markbokil.com/code/bottomfooter/
First, check the path you get with which emulator
and if you get /usr/local/share/android-sdk/tools/emulator
then remove or rename that emulator (it's an old one) and instead use /usr/local/share/android-sdk/emulator/emulator
which is the new path.
If you're using Homebrew and installed with brew cask install android-sdk android-studio
then you need to:
# Remove $HOME/Library/Android paths
# The new way is to use ANDROID_SDK_ROOT
export ANDROID_SDK_ROOT="/usr/local/share/android-sdk"
# For good measure, add old paths to be backwards compatible with any scripts or
whatnot. And to hopefully decrease confusion:
export ANDROID_HOME=$ANDROID_SDK_ROOT
export ANDROID_NDK_HOME=$ANDROID_SDK_ROOT/ndk-bundle
Then restart your terminal shell, and check your paths are as you expect them:
set | grep ANDROID
Finally, with correct paths set, you typically need to install the ndk and some tools:
sdkmanager "ndk-bundle" "cmake;3.10.2.4988404" "lldb;3.1"
and check the list for other pieces like this sdkmanager --list
I also closed Android Studio, removed the old Android/Sdk folder under my $HOME folder, and restarted Studio, and when it asked where my Sdk had gone, I pasted the Sdk path: /usr/local/share/android-sdk
div{_x000D_
height:100vh;_x000D_
}
_x000D_
<div></div>
_x000D_
we have to create your own docker volume mapped with the host directory before we mention in the docker-compose.yml as external
1.Create volume named share
docker volume create --driver local \
--opt type=none \
--opt device=/home/mukundhan/share \
--opt o=bind share
2.Use it in your docker-compose
version: "3"
volumes:
share:
external: true
services:
workstation:
container_name: "workstation"
image: "ubuntu"
stdin_open: true
tty: true
volumes:
- share:/share:consistent
- ./source:/source:consistent
working_dir: /source
ipc: host
privileged: true
shm_size: '2gb'
db:
container_name: "db"
image: "ubuntu"
stdin_open: true
tty: true
volumes:
- share:/share:consistent
working_dir: /source
ipc: host
This way we can share the same directory with many services running in different containers
PyCharm, definitely. I tried them all (almost), but PyCharm is the one I found most useful for any heavy development.
For simple, one time, scripts I use whatever comes to mind (TextMate, Vim, Emacs, TextWrangler, etc., you name it).
#footer:after
{
content: "";
width: 40px;
height: 3px;
background-color: #529600;
left: 0;
position: relative;
display: block;
top: 10px;
}
A reliable way to get the external IP address of the local machine would be to query the routing table, although we have no direct way to do it in PHP.
However we can get the system to do it for us by binding a UDP socket to a public address, and getting its address:
$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
socket_connect($sock, "8.8.8.8", 53);
socket_getsockname($sock, $name); // $name passed by reference
// This is the local machine's external IP address
$localAddr = $name;
socket_connect
will not cause any network traffic because it's an UDP socket.
this.PowerButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
alter table table_name
rename column old_column_name/field_name to new_column_name/field_name;
example: alter table student column name to username;
var res = (from element in list)
.OrderBy(x => x.F2).AsEnumerable()
.GroupBy(x => x.F1)
.Select()
Use .AsEnumerable() after OrderBy()
This is a follow up to the answer given by @EricWoodruff.
You could use netInfo
's getExtraInfo()
to get wifi SSID.
if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals (action)) {
NetworkInfo netInfo = intent.getParcelableExtra (WifiManager.EXTRA_NETWORK_INFO);
if (ConnectivityManager.TYPE_WIFI == netInfo.getType ()) {
String ssid = info.getExtraInfo()
Log.d(TAG, "WiFi SSID: " + ssid)
}
}
If you are not using BroadcastReceiver check this answer to get SSID using Context
This is tested on Android Oreo 8.1.0
Another way to get this error is by accidentally writing the definition of something in an anonymous namespace:
foo.h:
namespace foo {
void bar();
}
foo.cc:
namespace foo {
namespace { // wrong
void bar() { cout << "hello"; };
}
}
other.cc file:
#include "foo.h"
void baz() {
foo::bar();
}
PowerShell 3 has the $PSScriptRoot
automatic variable:
Contains the directory from which a script is being run.
In Windows PowerShell 2.0, this variable is valid only in script modules (.psm1). Beginning in Windows PowerShell 3.0, it is valid in all scripts.
Don't be fooled by the poor wording. PSScriptRoot
is the directory of the current file.
In PowerShell 2, you can calculate the value of $PSScriptRoot
yourself:
# PowerShell v2
$PSScriptRoot = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition
This should do the trick for ASP.NET. The concept is the same as shown in the PHP example. Since the URL is different everytime the script is loaded, neither browser of proxy should cache the file. I'm used to put my JavaScript code into separate files, and wasted a significant amount of time with Visual Studio until I realized that it wouldn't reload the JavaScript files.
<script src="Scripts/main.js?version=<% =DateTime.Now.Ticks.ToString()%>" type="text/javascript"></script>
Full example:
<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %> <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent"> <script src="Scripts/jquery-1.4.1-vsdoc.js" type="text/javascript"></script> <script src="Scripts/main.js?version=<% =DateTime.Now.Ticks.ToString()%>" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function () { myInit(); }); </script> </asp:Content>
Obvously, this solution should only be used during the development stage, and should be removed before posting the site.
I found a simple way
TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
RestTemplate restTemplate = new RestTemplate(requestFactory);
There's a Py library that has a module that facilitates access to Json-like dictionary key-values as attributes: https://github.com/asuiu/pyxtension You can use it as:
j = Json('{"lat":444, "lon":555}')
j.lat + ' ' + j.lon
You can use apache's commons-text library (instead of commons-lang):
Example code:
org.apache.commons.text.StringEscapeUtils.escapeJava(escapedString);
Dependency:
compile 'org.apache.commons:commons-text:1.8'
OR
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>1.8</version>
</dependency>
If you are certain that you have a JDK installed (and not a JRE), you can specify the location of the JDK on the commandline when starting the installer (as mentioned in the error message you get).
These FAQ entries might also help you:
http://wiki.netbeans.org/FaqInstallJavahome
http://wiki.netbeans.org/FaqSuitableJvmNotFound
Try using this instead:
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
It's bit hard to navigate Google's api but here is the relevant documentation.
One thing I had trouble finding was how to go in the other direction. From coordinates to an address. Here is the code I neded upp using. Please not that I also use jquery.
$.each(results[0].address_components, function(){
$("#CreateDialog").find('input[name="'+ this.types+'"]').attr('value', this.long_name);
});
What I'm doing is to loop through all the returned address_components
and test if their types match any input element names I have in a form. And if they do I set the value of the element to the address_components
value.
If you're only interrested in the whole formated address then you can follow Google's example
I cloned the following: https://github.com/google/play-licensing
Then I imported that into my project.
In my case Maximum call stack size exceeded
was triggered by another error earlier. The logs looked like this:
// ... skipping some deprecation warnings
> [email protected] postinstall /root/.nvm/versions/node/v14.10.0/lib/node_modules/@aws-amplify/cli/node_modules/amplify-graphql-types-generator/node_modules/core-js
> node -e "try{require('./postinstall')}catch(e){}"
sh: 1: node: Permission denied
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@~2.1.2 (node_modules/@aws-amplify/cli/node_modules/chokidar/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
npm ERR! Maximum call stack size exceeded
npm ERR! A complete log of this run can be found in:
npm ERR! /root/.npm/_logs/2020-09-10T14_10_28_397Z-debug.log
Note sh: 1: node: Permission denied
that led me to https://forum.vuejs.org/t/cannot-install-vue-cli-permission-error-in-require-postinstall/82017/7
I had to add --unsafe-perm
to the install command and run it as root:
sudo npm install -g --unsafe-perm @aws-amplify/cli
Due to my low reputation I couldn't comment on Derek ????'s answer. I've tried that code as it is and it didn't work well. There are three issues on Derek ????'s code.
The first is that the time to async send the request and change its property 'status' is slower than to execute the next expression - if(request.status === "404"). So the request.status will eventually, due to internet band, remain on status 0 (zero), and it won't achieve the code right below if. To fix that is easy: change 'true' to 'false' on method open of the ajax request. This will cause a brief (or not so) block on your code (due to synchronous call), but will change the status of the request before reaching the test on if.
The second is that the status is an integer. Using '===' javascript comparison operator you're trying to compare if the left side object is identical to one on the right side. To make this work there are two ways:
The third is that the object XMLHttpRequest only works on newer browsers (Firefox, Chrome and IE7+). If you want that snippet to work on all browsers you have to do in the way W3Schools suggests: w3schools ajax
The code that really worked for me was:
var request;
if(window.XMLHttpRequest)
request = new XMLHttpRequest();
else
request = new ActiveXObject("Microsoft.XMLHTTP");
request.open('GET', 'http://www.mozilla.org', false);
request.send(); // there will be a 'pause' here until the response to come.
// the object request will be actually modified
if (request.status === 404) {
alert("The page you are trying to reach is not available.");
}
I was having the same issue with font awesome v4.4 and I fixed it by removing the woff2 format. I was getting a warning in Chrome only.
@font-face {
font-family: 'FontAwesome';
src: url('../fonts/fontawesome-webfont.eot?v=4.4.0');
src: url('../fonts/fontawesome-webfont.eot?#iefix&v=4.4.0') format('embedded-opentype'), url('../fonts/fontawesome-webfont.woff?v=4.4.0') format('woff'), url('../fonts/fontawesome-webfont.ttf?v=4.4.0') format('truetype'), url('../fonts/fontawesome-webfont.svg?v=4.4.0#fontawesomeregular') format('svg');
font-weight: normal;
font-style: normal;
}
Service references deal with endpoints and bindings, which are completely configurable. They let you point your client proxy to a WCF via any transport protocol (HTTP, TCP, Shared Memory, etc)
They are designed to work with WCF.
If you use a WebProxy, you are pretty much binding yourself to using WCF over HTTP
That is usually all that you need to do...
Are you sure that after 20 minutes, the reason that the session is being lost is from being idle though...
There are many reasons as to why the session might be cleared. You can enable event logging for IIS and can then use the event viewer to see reasons why the session was cleared...you might find that it is for other reasons perhaps?
You can also read the documentation for event messages and the associated table of events.
To expand a bit on why the error happened: A forward slash at the beginning of a path means "start from the root of the filesystem, and look for the given path". No forward slash means "start from the current working directory, and look for the given path".
The path
/tmp/test.jpg
thus translates to looking for the file test.jpg in the tmp folder at the root of the filesystem (e.g. c:\ on windows, / on *nix), instead of the webapp folder. Adding a period (.) in front of the path explicitly changes this to read "start from the current working directory", but is basically the same as leaving the forward slash out completely.
./tmp/test.jpg = tmp/test.jpg
Java: SCJP for Java 6. I still use it as a reference.
If you truly want to discard the commits you've made locally, i.e. never have them in the history again, you're not asking how to pull - pull means merge, and you don't need to merge. All you need do is this:
# fetch from the default remote, origin
git fetch
# reset your current branch (master) to origin's master
git reset --hard origin/master
I'd personally recommend creating a backup branch at your current HEAD first, so that if you realize this was a bad idea, you haven't lost track of it.
If on the other hand, you want to keep those commits and make it look as though you merged with origin, and cause the merge to keep the versions from origin only, you can use the ours
merge strategy:
# fetch from the default remote, origin
git fetch
# create a branch at your current master
git branch old-master
# reset to origin's master
git reset --hard origin/master
# merge your old master, keeping "our" (origin/master's) content
git merge -s ours old-master
To show the div while selecting one value and hide while selecting another value from dropdown box: -
$('#yourselectorid').bind('change', function(event) {
var i= $('#yourselectorid').val();
if(i=="sometext") // equal to a selection option
{
$('#divid').show();
}
elseif(i=="othertext")
{
$('#divid').hide(); // hide the first one
$('#divid2').show(); // show the other one
}
});
This is something I wrote a few minutes ago just messing around. Hope it helps!
public class Main {
public static void main(String[] args) {
ArrayList<Integer> powers = new ArrayList<Integer>();
ArrayList<Integer> binaryStore = new ArrayList<Integer>();
powers.add(128);
powers.add(64);
powers.add(32);
powers.add(16);
powers.add(8);
powers.add(4);
powers.add(2);
powers.add(1);
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to Paden9000 binary converter. Please enter an integer you wish to convert: ");
int input = sc.nextInt();
int printableInput = input;
for (int i : powers) {
if (input < i) {
binaryStore.add(0);
} else {
input = input - i;
binaryStore.add(1);
}
}
String newString= binaryStore.toString();
String finalOutput = newString.replace("[", "")
.replace(" ", "")
.replace("]", "")
.replace(",", "");
System.out.println("Integer value: " + printableInput + "\nBinary value: " + finalOutput);
sc.close();
}
}
Using base graphics, the standard way to do this is to use axes=FALSE, then create your own axes using Axis (or axis). For example,
x <- 1:20
y <- runif(20)
plot(x, y, axes=FALSE, frame.plot=TRUE)
Axis(side=1, labels=FALSE)
Axis(side=2, labels=FALSE)
The lattice equivalent is
library(lattice)
xyplot(y ~ x, scales=list(alternating=0))
There are some nice answers on this question. I’ll try to add a more broad answer, namely about what these kinds of lines/headers/trailers are about in current practice. Not so much about the sign-off header in particular (it’s not the only one).
Headers or trailers (?1) like “sign-off” (?2) is, in current
practice in projects like Git and Linux, effectively structured metadata
for the commit. These are all appended to the end of the commit message,
after the “free form” (unstructured) part of the body of the message.
These are token–value (or key–value) pairs typically delimited by a
colon and a space (:?
).
Like I mentioned, “sign-off” is not the only trailer in current practice. See for example this commit, which has to do with “Dirty Cow”:
mm: remove gup_flags FOLL_WRITE games from __get_user_pages()
This is an ancient bug that was actually attempted to be fixed once
(badly) by me eleven years ago in commit 4ceb5db9757a ("Fix
get_user_pages() race for write access") but that was then undone due to
problems on s390 by commit f33ea7f404e5 ("fix get_user_pages bug").
In the meantime, the s390 situation has long been fixed, and we can now
fix it by checking the pte_dirty() bit properly (and do it better). The
s390 dirty bit was implemented in abf09bed3cce ("s390/mm: implement
software dirty bits") which made it into v3.9. Earlier kernels will
have to look at the page state itself.
Also, the VM has become more scalable, and what used a purely
theoretical race back then has become easier to trigger.
To fix it, we introduce a new internal FOLL_COW flag to mark the "yes,
we already did a COW" rather than play racy games with FOLL_WRITE that
is very fundamental, and then use the pte dirty flag to validate that
the FOLL_COW flag is still valid.
Reported-and-tested-by: Phil "not Paul" Oester <[email protected]>
Acked-by: Hugh Dickins <[email protected]>
Reviewed-by: Michal Hocko <[email protected]>
Cc: Andy Lutomirski <[email protected]>
Cc: Kees Cook <[email protected]>
Cc: Oleg Nesterov <[email protected]>
Cc: Willy Tarreau <[email protected]>
Cc: Nick Piggin <[email protected]>
Cc: Greg Thelen <[email protected]>
Cc: [email protected]
Signed-off-by: Linus Torvalds <[email protected]>
In addition to the “sign-off” trailer in the above, there is:
Other projects, like for example Gerrit, have their own headers and associated meaning for them.
See: https://git.wiki.kernel.org/index.php/CommitMessageConventions
It is my impression that, although the initial motivation for this particular metadata was some legal issues (judging by the other answers), the practice of such metadata has progressed beyond just dealing with the case of forming a chain of authorship.
[?1]: man git-interpret-trailers
[?2]: These are also sometimes called “s-o-b” (initials), it seems.
Something like this should do it for you.
Sub CombineColumns1()
Dim xRng As Range
Dim i As Long, j As Integer
Dim xNextRow As Long
Dim xTxt As String
On Error Resume Next
With ActiveSheet
xTxt = .RangeSelection.Address
Set xRng = Application.InputBox("please select the data range", "Kutools for Excel", xTxt, , , , , 8)
If xRng Is Nothing Then Exit Sub
j = xRng.Columns(1).Column
For i = 4 To xRng.Columns.Count Step 3
'Need to recalculate the last row, as some of the final columns may not have data in all rows
xNextRow = .Cells(.Rows.Count, j).End(xlUp).Row + 1
.Range(xRng.Cells(1, i), xRng.Cells(xRng.Rows.Count, i + 2)).Copy .Cells(xNextRow, j)
.Range(xRng.Cells(1, i), xRng.Cells(xRng.Rows.Count, i + 2)).Clear
Next
End With
End Sub
You could do this too.
Sub TransposeFormulas()
Dim vFormulas As Variant
Dim oSel As Range
If TypeName(Selection) <> "Range" Then
MsgBox "Please select a range of cells first.", _
vbOKOnly + vbInformation, "Transpose formulas"
Exit Sub
End If
Set oSel = Selection
vFormulas = oSel.Formula
vFormulas = Application.WorksheetFunction.Transpose(vFormulas)
oSel.Offset(oSel.Rows.Count + 2).Resize(oSel.Columns.Count, oSel.Rows.Count).Formula = vFormulas
End Sub
See this for more info.
Open the file for 'append' rather than 'write'.
with open('file.txt', 'a') as file:
file.write('input')
Using attr() pointing to an external domain may trigger an error like this in Chrome: "Refused to display document because display forbidden by X-Frame-Options". The workaround to this can be to move the whole iframe HTML code into the script (eg. using .html() in jQuery).
Example:
var divMapLoaded = false;
$("#container").scroll(function() {
if ((!divMapLoaded) && ($("#map").position().left <= $("#map").width())) {
$("#map-iframe").html("<iframe id=\"map-iframe\" " +
"width=\"100%\" height=\"100%\" frameborder=\"0\" scrolling=\"no\" " +
"marginheight=\"0\" marginwidth=\"0\" " +
"src=\"http://www.google.it/maps?t=m&cid=0x3e589d98063177ab&ie=UTF8&iwloc=A&brcurrent=5,0,1&ll=41.123115,16.853177&spn=0.005617,0.009943&output=embed\"" +
"></iframe>");
divMapLoaded = true;
}
For me when I created a file and saved it as python file, I was getting this error during importing. I had to create a filename with the type ".py" , like filename.py and then save it as a python file. post trying to import the file worked for me.
Try -
$("#column_select").change(function () {
$("#layout_select").children('option').hide();
$("#layout_select").children("option[value^=" + $(this).val() + "]").show()
})
If you were going to use this solution you'd need to hide all of the elements apart from the one with the 'none' value in your document.ready function -
$(document).ready(function() {
$("#layout_select").children('option:gt(0)').hide();
$("#column_select").change(function() {
$("#layout_select").children('option').hide();
$("#layout_select").children("option[value^=" + $(this).val() + "]").show()
})
})
Demo - http://jsfiddle.net/Mxkfr/2
EDIT
I might have got a bit carried away with this, but here's a further example that uses a cache of the original select list options to ensure that the 'layout_select' list is completely reset/cleared (including the 'none' option) after the 'column_select' list is changed -
$(document).ready(function() {
var optarray = $("#layout_select").children('option').map(function() {
return {
"value": this.value,
"option": "<option value='" + this.value + "'>" + this.text + "</option>"
}
})
$("#column_select").change(function() {
$("#layout_select").children('option').remove();
var addoptarr = [];
for (i = 0; i < optarray.length; i++) {
if (optarray[i].value.indexOf($(this).val()) > -1) {
addoptarr.push(optarray[i].option);
}
}
$("#layout_select").html(addoptarr.join(''))
}).change();
})
Demo - http://jsfiddle.net/N7Xpb/1/
Your created_date field is datetime
, so you'll need to strip off the time before the grouping will work if you want to go by date:
SELECT COUNT(created_date), created_date
FROM table
WHERE DATEDIFF(created_date, getdate()) < 10
GROUP BY convert(varchar, created_date, 101)
The following code is looking for '\0', and under the assumptions of the question the array can be considered sorted since all non-'\0' precede all '\0'. This assumption won't hold if the array can contain '\0' within the data.
Find the location of the first zero-byte using a binary search, then slice.
You can find the zero-byte like this:
package main
import "fmt"
func FirstZero(b []byte) int {
min, max := 0, len(b)
for {
if min + 1 == max { return max }
mid := (min + max) / 2
if b[mid] == '\000' {
max = mid
} else {
min = mid
}
}
return len(b)
}
func main() {
b := []byte{1, 2, 3, 0, 0, 0}
fmt.Println(FirstZero(b))
}
It may be faster just to naively scan the byte array looking for the zero-byte, especially if most of your strings are short.
Check the document encoding.
I had this same problem. I develop on Windows XP using Notepad++ and WampServer to run Apache locally and all was fine. After uploading to hosting provider that uses Apache on Unix I got this error. I had no extra PHP tags or white-space from extra lines after the closing tag.
For me this was caused by the encoding of the text documents. I used the "Convert to UTF-8 without BOM" option in Notepad++(under Encoding tab) and reloaded to the web server. Problem fixed, no code/editing changes required.
If you want not to strip, but to actually convert latin accented to non-accented characters, take a look at this question: How do I translate 8bit characters into 7bit characters? (i.e. Ü to U)
Use a comma ","
eg:
UPDATE my_table SET rowOneValue = rowOneValue + 1, rowTwoValue = rowTwoValue + ( (rowTwoValue / (rowTwoValue) ) + ?) * (v + 1) WHERE value = ?
You should be able to generate your own button code here: http://developers.facebook.com/docs/reference/plugins/like/
To guarantee that the type is an Object
(i.e. key-value pairs), use:
const obj: {[x: string]: any} = {}
obj.prop = 'cool beans'
DECLARE @IDQuery VARCHAR(MAX)
SET @IDQuery = 'SELECT ID FROM SomeTable WHERE Condition=Something'
DECLARE @ExcludedList TABLE(ID VARCHAR(MAX))
INSERT INTO @ExcludedList EXEC(@IDQuery)
SELECT * FROM A WHERE Id NOT IN (@ExcludedList)
I know I'm responding to an old post but I wanted to share an example of how to use Variable Tables when one wants to avoid using dynamic SQL. I'm not sure if its the most efficient way, however this has worked in the past for me when dynamic SQL was not an option.
You don't have to do a replace, you can get the length of the children text and subtract that from the overall length, and slice into the original text. That should be substantially faster.
If you want to hide gridlines but want to show yAxes, you can set:
yAxes: [{...
gridLines: {
drawBorder: true,
display: false
}
}]
In your html :
<a href="javascript:void(0);" ng-click="go_back()">Go Back</a>
On your main controller :
$scope.go_back = function() {
$window.history.back();
};
When user click on Go Back link the controller function is called and it will go back to previous route.
Here is a solution handling all Unicode code points include upper (4 byte) values and supported by all modern browsers (IE and others > 5.5). It uses decodeURIComponent(), but NOT the deprecated escape/unescape functions:
function utf8_to_str(a) {
for(var i=0, s=''; i<a.length; i++) {
var h = a[i].toString(16)
if(h.length < 2) h = '0' + h
s += '%' + h
}
return decodeURIComponent(s)
}
Tested and available on GitHub
To create UTF-8 from a string:
function utf8_from_str(s) {
for(var i=0, enc = encodeURIComponent(s), a = []; i < enc.length;) {
if(enc[i] === '%') {
a.push(parseInt(enc.substr(i+1, 2), 16))
i += 3
} else {
a.push(enc.charCodeAt(i++))
}
}
return a
}
Tested and available on GitHub
DECLARE @TABLE TABLE
(RowNo INT,ScripName VARCHAR(10),ScripCode VARCHAR(10)
,Price VARCHAR(10))
INSERT INTO @TABLE VALUES
(1,'20 MICRONS ','533022','39')
SELECT ColumnName,ColumnValue from @Table
Unpivot(ColumnValue For ColumnName IN (ScripName,ScripCode,Price)) AS H
I am linking to what essentially is the same discussion where Peter Lawrey is providing a good answer. Why I get a negative elapsed time using System.nanoTime()?
Many people mentioned that in Java System.nanoTime() could return negative time. I for apologize for repeating what other people already said.
It'd be cool if System.nanoTime() returned coreID where it executed.
If you just want to see what's installed on the machine you're currently logged in to, I think the most straightforward manual process is to just open the SQL Server Configuration Manager (from the Start menu), which displays all the SQL Services (and only SQL services) on that hardware (running or not). This assumes SQL Server 2005, or greater; dotnetengineer's recommendation to use the Services Management Console will show you all services, and should always be available (if you're running earlier versions of SQL Server, for example).
If you're looking for a broader discovery process, however, you might consider third party tools such as SQLRecon and SQLPing, which will scan your network and build a report of all SQL Service instances found on any server to which they have access. It's been a while since I've used tools like this, but I was surprised at what they found (namely, a handful of instances that I didn't know existed). YMMV. You might Google for details, but I believe this page has the relevant downloads: http://www.sqlsecurity.com/Tools/FreeTools/tabid/65/Default.aspx
Run the following command in terminal:
sudo ln -s /usr/share/phpmyadmin /var/www/html/
Why you make it so hard to understand?
function table_exist($table){
$pTableExist = mysql_query("show tables like '".$table."'");
if ($rTableExist = mysql_fetch_array($pTableExist)) {
return "Yes";
}else{
return "No";
}
}
As other answers have pointed, on UNIX systems the numbers represent CPU load averages over 1/5/15 minute periods. But on Linux (and consequently Android), what it represents is something different.
After a kernel patch dating back to 1993 (a great in-depth article on the subject), in Linux the load average numbers no longer strictly represent the CPU load: as the calculation accounts not only for CPU bound processes, but also for processes in uninterruptible wait state - the original goal was to account for I/O bound processes this way, to represent more of a "system load" than just CPU load. The issue is that since 1993 the usage of uninterruptible state has grown in Linux kernel, and it no longer typically represents an I/O bound process. The problem is further exacerbated by some Linux devs using uninterruptible waits as an easy wait to avoid accommodating signals in their implementations. As a result, in Linux (and Android) we can see skewed high load average numbers that do not objectively represent the real load. There are Android user reports about unreasonable high load averages contrasting low CPU utilization. For example, my old Android phone (with 2 CPU cores) normally shown average load of ~12 even when the system and CPUs were idle. Hence, average load numbers in Linux (Android) does not turn out to be a reliable performance metric.
$("#checkbox").change(function(e) {
if ($(this).prop('checked')){
console.log('checked');
}
});
When you call test
with &nKByte
, the address-of operator creates a temporary value, and you can't normally have references to temporary values because they are, well, temporary.
Either do not use a reference for the argument, or better yet don't use a pointer.
Be careful how you define the table for you will get different results on insert. Consider the following
CREATE TABLE IF NOT EXISTS t1 (id INTEGER PRIMARY KEY, a TEXT UNIQUE, b TEXT);
INSERT INTO t1 (a, b) VALUES
('Alice', 'Some title'),
('Bob', 'Palindromic guy'),
('Charles', 'chucky cheese'),
('Alice', 'Some other title')
ON CONFLICT(a) DO UPDATE SET b=excluded.b;
CREATE TABLE IF NOT EXISTS t2 (id INTEGER PRIMARY KEY, a TEXT UNIQUE, b TEXT, UNIQUE(a) ON CONFLICT REPLACE);
INSERT INTO t2 (a, b) VALUES
('Alice', 'Some title'),
('Bob', 'Palindromic guy'),
('Charles', 'chucky cheese'),
('Alice', 'Some other title');
$ sqlite3 test.sqlite
SQLite version 3.28.0 2019-04-16 19:49:53
Enter ".help" for usage hints.
sqlite> CREATE TABLE IF NOT EXISTS t1 (id INTEGER PRIMARY KEY, a TEXT UNIQUE, b TEXT);
sqlite> INSERT INTO t1 (a, b) VALUES
...> ('Alice', 'Some title'),
...> ('Bob', 'Palindromic guy'),
...> ('Charles', 'chucky cheese'),
...> ('Alice', 'Some other title')
...> ON CONFLICT(a) DO UPDATE SET b=excluded.b;
sqlite> CREATE TABLE IF NOT EXISTS t2 (id INTEGER PRIMARY KEY, a TEXT UNIQUE, b TEXT, UNIQUE(a) ON CONFLICT REPLACE);
sqlite> INSERT INTO t2 (a, b) VALUES
...> ('Alice', 'Some title'),
...> ('Bob', 'Palindromic guy'),
...> ('Charles', 'chucky cheese'),
...> ('Alice', 'Some other title');
sqlite> .mode col
sqlite> .headers on
sqlite> select * from t1;
id a b
---------- ---------- ----------------
1 Alice Some other title
2 Bob Palindromic guy
3 Charles chucky cheese
sqlite> select * from t2;
id a b
---------- ---------- ---------------
2 Bob Palindromic guy
3 Charles chucky cheese
4 Alice Some other titl
sqlite>
While the insert/update effect is the same, the id
changes based on the table definition type (see the second table where 'Alice' now has id = 4
; the first table is doing more of what I expect it to do, keep the PRIMARY KEY the same). Be aware of this effect.
One of the easiest solution is
$objectData = (object) $arrayData
Slight change to @rejesh-yadav wonderful answer.
html2canvas now returns a promise.
html2canvas(document.body).then(function (canvas) {
var img = canvas.toDataURL("image/png");
var doc = new jsPDF();
doc.addImage(img, 'JPEG', 10, 10);
doc.save('test.pdf');
});
Hope this helps some!
You can use the run command and specify your services to run. Be careful, the run command does not expose ports to the host. You should use the flag --service-ports
to do that if needed.
docker-compose run --service-ports client server database
Why don't you create a new object right in the .Select
:
.Select(x => new PInfo{
ServerName = x.ServerName,
ProcessID = x.ProcessID,
UserName = x.Username }).ToList();
The problem is the tv.setText(text)
. The variable tv is probably null
and you call the setText
method on that null
, which you can't.
My guess that the problem is on the findViewById
method, but it's not here, so I can't tell more, without the code.
This is my working code:
@Html.EditorFor(model => model.PropertyName, new { htmlAttributes = new { @class = "form-control", @Value = "123" } })
my difference with other answers is using Value inside the htmlAttributes array
For now, until there is something new from EFCore I would used a command and map it manually
using (var command = this.DbContext.Database.GetDbConnection().CreateCommand())
{
command.CommandText = "SELECT ... WHERE ...> @p1)";
command.CommandType = CommandType.Text;
var parameter = new SqlParameter("@p1",...);
command.Parameters.Add(parameter);
this.DbContext.Database.OpenConnection();
using (var result = command.ExecuteReader())
{
while (result.Read())
{
.... // Map to your entity
}
}
}
Try to SqlParameter to avoid Sql Injection.
dbData.Product.FromSql("SQL SCRIPT");
FromSql doesn't work with full query. Example if you want to include a WHERE clause it will be ignored.
Some Links:
I've always used sort_by
. You need to wrap the #sort_by
output with Hash[]
to make it output a hash, otherwise it outputs an array of arrays. Alternatively, to accomplish this you can run the #to_h
method on the array of tuples to convert them to a k=>v
structure (hash).
hsh ={"a" => 1000, "b" => 10, "c" => 200000}
Hash[hsh.sort_by{|k,v| v}] #or hsh.sort_by{|k,v| v}.to_h
There is a similar question in "How to sort a Ruby Hash by number value?".
It's important to note, that NULL doesn't equal NULL.
NULL
is not a value, and therefore cannot be compared to another value.
where x is null
checks whether x is a null value.
where x = null
is checking whether x equals NULL, which will never be true
This works. You create a method on Array by using prototype.
if (Array.prototype.allValuesSame === undefined) {
Array.prototype.allValuesSame = function() {
for (let i = 1; i < this.length; i++) {
if (this[i] !== this[0]) {
return false;
}
}
return true;
}
}
Call this in this way:
let a = ['a', 'a', 'a'];
let b = a.allValuesSame(); // true
a = ['a', 'b', 'a'];
b = a.allValuesSame(); // false
Not mentioned but can help in some instances:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState !== 4) return;
if (xhr.status === 200) {
var doc = iframe.contentWindow.document;
doc.open();
doc.write(xhr.responseText);
doc.close();
}
}
xhr.open('GET', url, true);
xhr.send(null);
For simple cases, we could redirect the Standard Out (STDOUT) and Standard Error (STDERR) streams directly to a file(say, test.log) using '>' and '2>&1'
Example:
// test.js
(function() {
// Below outputs are sent to Standard Out (STDOUT) stream
console.log("Hello Log");
console.info("Hello Info");
// Below outputs are sent to Standard Error (STDERR) stream
console.error("Hello Error");
console.warn("Hello Warning");
})();
node test.js > test.log 2>&1
As per the POSIX standard, 'input', 'output' and 'error' streams are identified by the positive integer file descriptors (0, 1, 2). i.e., stdin is 0, stdout is 1, and stderr is 2.
Step 1: '2>&1' will redirect from 2 (stderr) to 1 (stdout)
Step 2: '>' will redirect from 1 (stdout) to file (test.log)
As of PHP 7.0 type declarations allow scalar types, so these types are now available: self
, array
, callable
, bool
, float
, int
, string
. The first three were available in PHP 5, but the last four are new in PHP 7. If you use anything else (e.g. integer
or boolean
) that will be interpreted as a class name.
You probably want to look at something like URL Rewrite to rewrite URLs to more user friendly ones rather than using a simple httpRedirect
. You could then make a rule like this:
<system.webServer>
<rewrite>
<rules>
<rule name="Rewrite to Category">
<match url="^Category/([_0-9a-z-]+)/([_0-9a-z-]+)" />
<action type="Rewrite" url="category.aspx?cid={R:2}" />
</rule>
</rules>
</rewrite>
</system.webServer>
Office 2007 .docx should be possible since it's an XML standard. Word 2003 most likely requires COM to read, even with the standards now published by MS, since those standards are huge. I haven't seen many libraries written to match them yet.
function alertWithoutNotice(message){
setTimeout(function(){
alert(message);
}, 1000);
}
Can't you implement your own timeout system?
Keep a sorted list, or better yet a priority heap as Heath suggests, of timeout events. In your select or poll calls use the timeout value from the top of the timeout list. When that timeout arrives, do that action attached to that timeout.
That action could be closing a socket that hasn't connected yet.
As David says, mp3wrap is the way to go. However, I found that it didn't fix the audio length header, so iTunes refused to play the whole file even though all the data was there. (I merged three 7-minute files, but it only saw up to the first 7 minutes.)
I dug up this blog post, which explains how to fix this and also how to copy the ID3 tags over from the original files (on its own, mp3wrap deletes your ID3 tags). Or to just copy the tags (using id3cp from id3lib), do:
id3cp original.mp3 new.mp3
1.if your phone system is over 4.2.2 , there will be
2.disconnect the USB and try again or restart your phone
3.After after all try , it didn't work. It may be a shortage power supply so try other usb interface on your computer.
I solved the problem doing the first step . anyway have try.
Create a UITextView inside of a tableViewController. I used function: textViewDidChange and then checked for return-key-input. then if it detected return-key-input, delete the input of return key and dismiss keyboard.
func textViewDidChange(_ textView: UITextView) {
tableView.beginUpdates()
if textView.text.contains("\n"){
textView.text.remove(at: textView.text.index(before: textView.text.endIndex))
textView.resignFirstResponder()
}
tableView.endUpdates()
}
Checkout the branch for which you would like to squash all the commits into one commit. Let's say it's called feature_branch
.
git checkout feature_branch
Do a soft reset of your origin/feature_branch
with your local main
branch (depending on your needs, you can reset with origin/main as well). This will reset all the extra commits in your feature_branch
, but without changing any of your file changes locally.
git reset --soft main
Add all of the changes in your git repo directory, to the new commit that is going to be created. And commit the same with a message.
git add -A && git commit -m "commit message goes here"
When you press enter in a form the natural behaviour of form is to being submited, to stop this behaviour which is not natural, you have to prevent it from submiting( default behaviour), with jquery:
$("#yourFormId").on("submit",function(event){event.preventDefault()})
Make sure Blog
has methods equals(Object)
and hashCode()
defined, and addAll(list)
then to a new HashSet()
, or new LinkedHashSet()
if the order is important.
Better yet, use a Set
instead of a List
from the start, since you obviously don't want duplicates, it's better that your data model reflects that rather than having to remove them after the fact.
Why not using attribute "disabled" in css. This must works on all browsers.
button[disabled]:hover {
background: red;
}
button:hover {
background: lime;
}
A late answer here, but I've used
DECIMAL(13,2)
which I'm right in thinking should allow upto 99,999,999,999.99.
I'd set up your HTML like so:
<img src="../images/bottle.jpg" alt="bottle" class="thumbnails" id="bottle" />
Then use the following code:
<script>
var images = document.getElementsByTagName("img");
for(var i = 0; i < images.length; i++) {
var image = images[i];
image.onclick = function(event) {
window.location.href = this.id + '.html';
};
}
</script>
That assigns an onclick
event handler to every image on the page (this may not be what you want, you can limit it further if necessary) that changes the current page to the value of the images id
attribute plus the .html
extension. It's essentially the pure Javascript implementation of @JanPöschko's jQuery answer.
Starting with NUnit 2.5 you can use /framework switch e.g.:
nunit-console myassembly.dll /framework:net-1.1
This is from NUnit's help pages.
This can be massively simplified with just 1 line of code in viewDidAppear:
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
tableViewHeightConstraint.constant = tableView.contentSize.height
}
while STDIN.gets
puts $_
end
while ARGF.gets
puts $_
end
This is inspired by Perl:
while(<STDIN>){
print "$_\n"
}
Use "External data" from Excel. It can use ODBC connection to fetch data from external source: Data/Get External Data/New Database Query
That way, even if the data in the database changes, you can easily refresh.
The typical form for dynamically allocating an NxM array of type T is
T **a = malloc(sizeof *a * N);
if (a)
{
for (i = 0; i < N; i++)
{
a[i] = malloc(sizeof *a[i] * M);
}
}
If each element of the array has a different length, then replace M with the appropriate length for that element; for example
T **a = malloc(sizeof *a * N);
if (a)
{
for (i = 0; i < N; i++)
{
a[i] = malloc(sizeof *a[i] * length_for_this_element);
}
}
The above examples trivialized the problem of calculating differences. Assuming sorting or de-duplication definitely make it easier to compute the difference, but if your comparison cannot afford those assumptions then you'll need a non-trivial implementation of a diff algorithm. See difflib in the python standard library.
#! /usr/bin/python2
from difflib import SequenceMatcher
A = [1,2,3,4]
B = [2,5]
squeeze=SequenceMatcher( None, A, B )
print "A - B = [%s]"%( reduce( lambda p,q: p+q,
map( lambda t: squeeze.a[t[1]:t[2]],
filter(lambda x:x[0]!='equal',
squeeze.get_opcodes() ) ) ) )
Or Python3...
#! /usr/bin/python3
from difflib import SequenceMatcher
from functools import reduce
A = [1,2,3,4]
B = [2,5]
squeeze=SequenceMatcher( None, A, B )
print( "A - B = [%s]"%( reduce( lambda p,q: p+q,
map( lambda t: squeeze.a[t[1]:t[2]],
filter(lambda x:x[0]!='equal',
squeeze.get_opcodes() ) ) ) ) )
Output:
A - B = [[1, 3, 4]]
For my condition the cause was taking int
parameter for TextView
. Let me show an example
int i = 5;
myTextView.setText(i);
gets the error info above.
This can be fixed by converting int
to String
like this
myTextView.setText(String.valueOf(i));
As you write int
, it expects a resource not the text that you are writing. So be careful on setting an int
as a String
in Android.
Please add Settings under Properties for the Project and make use of them this way you have clean and easy configurable settings that can be configured as default
How To: Create a New Setting at Design Time
Update: after comments below
- Right + Click on project
- Add New Item
- Under Visual C# Items -> General
- Select Settings File
Very useful I had a slightly different scenario where I the request xml was itself the body of the POST and not a param. For that the following code can be used - Posting as an answer just in case anyone else having similar issue will benefit.
final HttpHeaders headers = new HttpHeaders();
headers.add("header1", "9998");
headers.add("username", "xxxxx");
headers.add("password", "xxxxx");
headers.add("header2", "yyyyyy");
headers.add("header3", "zzzzz");
headers.setContentType(MediaType.APPLICATION_XML);
headers.setAccept(Arrays.asList(MediaType.APPLICATION_XML));
final HttpEntity<MyXmlbeansRequestDocument> httpEntity = new HttpEntity<MyXmlbeansRequestDocument>(
MyXmlbeansRequestDocument.Factory.parse(request), headers);
final ResponseEntity<MyXmlbeansResponseDocument> responseEntity = restTemplate.exchange(url, HttpMethod.POST, httpEntity,MyXmlbeansResponseDocument.class);
log.info(responseEntity.getBody());
A couple solutions for async loading:
//this function will work cross-browser for loading scripts asynchronously
function loadScript(src, callback)
{
var s,
r,
t;
r = false;
s = document.createElement('script');
s.type = 'text/javascript';
s.src = src;
s.onload = s.onreadystatechange = function() {
//console.log( this.readyState ); //uncomment this line to see which ready states are called.
if ( !r && (!this.readyState || this.readyState == 'complete') )
{
r = true;
callback();
}
};
t = document.getElementsByTagName('script')[0];
t.parentNode.insertBefore(s, t);
}
If you've already got jQuery on the page, just use:
$.getScript(url, successCallback)
*
Additionally, it's possible that your scripts are being loaded/executed before the document is done loading, meaning that you'd need to wait for document.ready
before events can be bound to the elements.
It's not possible to tell specifically what your issue is without seeing the code.
The simplest solution is to keep all of your scripts inline at the bottom of the page, that way they don't block the loading of HTML content while they execute. It also avoids the issue of having to asynchronously load each required script.
If you have a particularly fancy interaction that isn't always used that requires a larger script of some sort, it could be useful to avoid loading that particular script until it's needed (lazy loading).
* scripts loaded with $.getScript
will likely not be cached
For anyone who can use modern features such as the Promise
object, the loadScript
function has become significantly simpler:
function loadScript(src) {
return new Promise(function (resolve, reject) {
var s;
s = document.createElement('script');
s.src = src;
s.onload = resolve;
s.onerror = reject;
document.head.appendChild(s);
});
}
Be aware that this version no longer accepts a callback
argument as the returned promise will handle callback. What previously would have been loadScript(src, callback)
would now be loadScript(src).then(callback)
.
This has the added bonus of being able to detect and handle failures, for example one could call...
loadScript(cdnSource)
.catch(loadScript.bind(null, localSource))
.then(successCallback, failureCallback);
...and it would handle CDN outages gracefully.
One issue you might run into is is_home()
returns true when a registered query_var is present in the home URL. For example, if http://example.com
displays a static page instead of the blog, http://example.com/?c=123
will return the blog.
See https://core.trac.wordpress.org/ticket/25143 and https://wordpress.org/support/topic/adding-query-var-makes-front-page-missing/ for more info on this.
What you can do (if you're not attempting to affect the query) is use add_rewrite_endpoint()
. It should be run during the init
action as it affects the rewrite rules. Eg.
add_action( 'init', 'add_custom_setcookie_rewrite_endpoints' );
function add_custom_setcookie_rewrite_endpoints() {
//add ?c=123 endpoint with
//EP_ALL so endpoint is present across all places
//no effect on the query vars
add_rewrite_endpoint( 'c', EP_ALL, $query_vars = false );
}
This should give you access to $_GET['c']
when the url contains more information like www.example.com/news?c=123
.
Remember to flush your rewrite rules after adding/modifying this.
You can try
>>> import statlib
>>> print statlib.__version__
>>> import construct
>>> print contruct.__version__
Update: This is the approach recommended by PEP 396. But that PEP was never accepted and has been deferred. In fact, there appears to be increasing support amongst Python core developers to recommend not including a __version__
attribute, e.g. in https://gitlab.com/python-devs/importlib_metadata/-/merge_requests/125.
Direct conversion from jks to pem file using the keytool
keytool -exportcert -alias selfsigned -keypass password -keystore test-user.jks -rfc -file test-user.pem
path = "C:\\Users\\Programming\\Downloads"
# Replace \\ with a \ along with any random key multiple times
path.replace('\\', '\pppyyyttthhhooonnn')
# Now replace pppyyyttthhhooonnn with a blank string
path.replace("pppyyyttthhhooonnn", "")
print(path)
#Output... C:\Users\Programming\Downloads
In modern MongoDB releases you can brute force this with $slice
just off the basic aggregation result. For "large" results, run parallel queries instead for each grouping ( a demonstration listing is at the end of the answer ), or wait for SERVER-9377 to resolve, which would allow a "limit" to the number of items to $push
to an array.
db.books.aggregate([
{ "$group": {
"_id": {
"addr": "$addr",
"book": "$book"
},
"bookCount": { "$sum": 1 }
}},
{ "$group": {
"_id": "$_id.addr",
"books": {
"$push": {
"book": "$_id.book",
"count": "$bookCount"
},
},
"count": { "$sum": "$bookCount" }
}},
{ "$sort": { "count": -1 } },
{ "$limit": 2 },
{ "$project": {
"books": { "$slice": [ "$books", 2 ] },
"count": 1
}}
])
Still not resolving SERVER-9377, but in this release $lookup
allows a new "non-correlated" option which takes an "pipeline"
expression as an argument instead of the "localFields"
and "foreignFields"
options. This then allows a "self-join" with another pipeline expression, in which we can apply $limit
in order to return the "top-n" results.
db.books.aggregate([
{ "$group": {
"_id": "$addr",
"count": { "$sum": 1 }
}},
{ "$sort": { "count": -1 } },
{ "$limit": 2 },
{ "$lookup": {
"from": "books",
"let": {
"addr": "$_id"
},
"pipeline": [
{ "$match": {
"$expr": { "$eq": [ "$addr", "$$addr"] }
}},
{ "$group": {
"_id": "$book",
"count": { "$sum": 1 }
}},
{ "$sort": { "count": -1 } },
{ "$limit": 2 }
],
"as": "books"
}}
])
The other addition here is of course the ability to interpolate the variable through $expr
using $match
to select the matching items in the "join", but the general premise is a "pipeline within a pipeline" where the inner content can be filtered by matches from the parent. Since they are both "pipelines" themselves we can $limit
each result separately.
This would be the next best option to running parallel queries, and actually would be better if the $match
were allowed and able to use an index in the "sub-pipeline" processing. So which is does not use the "limit to $push
" as the referenced issue asks, it actually delivers something that should work better.
You seem have stumbled upon the top "N" problem. In a way your problem is fairly easy to solve though not with the exact limiting that you ask for:
db.books.aggregate([
{ "$group": {
"_id": {
"addr": "$addr",
"book": "$book"
},
"bookCount": { "$sum": 1 }
}},
{ "$group": {
"_id": "$_id.addr",
"books": {
"$push": {
"book": "$_id.book",
"count": "$bookCount"
},
},
"count": { "$sum": "$bookCount" }
}},
{ "$sort": { "count": -1 } },
{ "$limit": 2 }
])
Now that will give you a result like this:
{
"result" : [
{
"_id" : "address1",
"books" : [
{
"book" : "book4",
"count" : 1
},
{
"book" : "book5",
"count" : 1
},
{
"book" : "book1",
"count" : 3
}
],
"count" : 5
},
{
"_id" : "address2",
"books" : [
{
"book" : "book5",
"count" : 1
},
{
"book" : "book1",
"count" : 2
}
],
"count" : 3
}
],
"ok" : 1
}
So this differs from what you are asking in that, while we do get the top results for the address values the underlying "books" selection is not limited to only a required amount of results.
This turns out to be very difficult to do, but it can be done though the complexity just increases with the number of items you need to match. To keep it simple we can keep this at 2 matches at most:
db.books.aggregate([
{ "$group": {
"_id": {
"addr": "$addr",
"book": "$book"
},
"bookCount": { "$sum": 1 }
}},
{ "$group": {
"_id": "$_id.addr",
"books": {
"$push": {
"book": "$_id.book",
"count": "$bookCount"
},
},
"count": { "$sum": "$bookCount" }
}},
{ "$sort": { "count": -1 } },
{ "$limit": 2 },
{ "$unwind": "$books" },
{ "$sort": { "count": 1, "books.count": -1 } },
{ "$group": {
"_id": "$_id",
"books": { "$push": "$books" },
"count": { "$first": "$count" }
}},
{ "$project": {
"_id": {
"_id": "$_id",
"books": "$books",
"count": "$count"
},
"newBooks": "$books"
}},
{ "$unwind": "$newBooks" },
{ "$group": {
"_id": "$_id",
"num1": { "$first": "$newBooks" }
}},
{ "$project": {
"_id": "$_id",
"newBooks": "$_id.books",
"num1": 1
}},
{ "$unwind": "$newBooks" },
{ "$project": {
"_id": "$_id",
"num1": 1,
"newBooks": 1,
"seen": { "$eq": [
"$num1",
"$newBooks"
]}
}},
{ "$match": { "seen": false } },
{ "$group":{
"_id": "$_id._id",
"num1": { "$first": "$num1" },
"num2": { "$first": "$newBooks" },
"count": { "$first": "$_id.count" }
}},
{ "$project": {
"num1": 1,
"num2": 1,
"count": 1,
"type": { "$cond": [ 1, [true,false],0 ] }
}},
{ "$unwind": "$type" },
{ "$project": {
"books": { "$cond": [
"$type",
"$num1",
"$num2"
]},
"count": 1
}},
{ "$group": {
"_id": "$_id",
"count": { "$first": "$count" },
"books": { "$push": "$books" }
}},
{ "$sort": { "count": -1 } }
])
So that will actually give you the top 2 "books" from the top two "address" entries.
But for my money, stay with the first form and then simply "slice" the elements of the array that are returned to take the first "N" elements.
The demonstration code is appropriate for usage with current LTS versions of NodeJS from v8.x and v10.x releases. That's mostly for the async/await
syntax, but there is nothing really within the general flow that has any such restriction, and adapts with little alteration to plain promises or even back to plain callback implementation.
index.js
const { MongoClient } = require('mongodb');
const fs = require('mz/fs');
const uri = 'mongodb://localhost:27017';
const log = data => console.log(JSON.stringify(data, undefined, 2));
(async function() {
try {
const client = await MongoClient.connect(uri);
const db = client.db('bookDemo');
const books = db.collection('books');
let { version } = await db.command({ buildInfo: 1 });
version = parseFloat(version.match(new RegExp(/(?:(?!-).)*/))[0]);
// Clear and load books
await books.deleteMany({});
await books.insertMany(
(await fs.readFile('books.json'))
.toString()
.replace(/\n$/,"")
.split("\n")
.map(JSON.parse)
);
if ( version >= 3.6 ) {
// Non-correlated pipeline with limits
let result = await books.aggregate([
{ "$group": {
"_id": "$addr",
"count": { "$sum": 1 }
}},
{ "$sort": { "count": -1 } },
{ "$limit": 2 },
{ "$lookup": {
"from": "books",
"as": "books",
"let": { "addr": "$_id" },
"pipeline": [
{ "$match": {
"$expr": { "$eq": [ "$addr", "$$addr" ] }
}},
{ "$group": {
"_id": "$book",
"count": { "$sum": 1 },
}},
{ "$sort": { "count": -1 } },
{ "$limit": 2 }
]
}}
]).toArray();
log({ result });
}
// Serial result procesing with parallel fetch
// First get top addr items
let topaddr = await books.aggregate([
{ "$group": {
"_id": "$addr",
"count": { "$sum": 1 }
}},
{ "$sort": { "count": -1 } },
{ "$limit": 2 }
]).toArray();
// Run parallel top books for each addr
let topbooks = await Promise.all(
topaddr.map(({ _id: addr }) =>
books.aggregate([
{ "$match": { addr } },
{ "$group": {
"_id": "$book",
"count": { "$sum": 1 }
}},
{ "$sort": { "count": -1 } },
{ "$limit": 2 }
]).toArray()
)
);
// Merge output
topaddr = topaddr.map((d,i) => ({ ...d, books: topbooks[i] }));
log({ topaddr });
client.close();
} catch(e) {
console.error(e)
} finally {
process.exit()
}
})()
books.json
{ "addr": "address1", "book": "book1" }
{ "addr": "address2", "book": "book1" }
{ "addr": "address1", "book": "book5" }
{ "addr": "address3", "book": "book9" }
{ "addr": "address2", "book": "book5" }
{ "addr": "address2", "book": "book1" }
{ "addr": "address1", "book": "book1" }
{ "addr": "address15", "book": "book1" }
{ "addr": "address9", "book": "book99" }
{ "addr": "address90", "book": "book33" }
{ "addr": "address4", "book": "book3" }
{ "addr": "address5", "book": "book1" }
{ "addr": "address77", "book": "book11" }
{ "addr": "address1", "book": "book1" }
With the new ES6/ES2015 features, you don't have to use an object anymore to iterate over a hash. You can use a Map. Javascript Maps keep keys in insertion order, meaning you can iterate over them without having to check the hasOwnProperty, which was always really a hack.
Iterate over a map:
var myMap = new Map();
myMap.set(0, "zero");
myMap.set(1, "one");
for (var [key, value] of myMap) {
console.log(key + " = " + value);
}
// Will show 2 logs; first with "0 = zero" and second with "1 = one"
for (var key of myMap.keys()) {
console.log(key);
}
// Will show 2 logs; first with "0" and second with "1"
for (var value of myMap.values()) {
console.log(value);
}
// Will show 2 logs; first with "zero" and second with "one"
for (var [key, value] of myMap.entries()) {
console.log(key + " = " + value);
}
// Will show 2 logs; first with "0 = zero" and second with "1 = one"
or use forEach:
myMap.forEach(function(value, key) {
console.log(key + " = " + value);
}, myMap)
// Will show 2 logs; first with "0 = zero" and second with "1 = one"
I create a file dif.go
that contains your code:
package dif
import (
"time"
)
var StartTime = time.Now()
Outside the folder I create my main.go
, it is ok!
package main
import (
dif "./dif"
"fmt"
)
func main() {
fmt.Println(dif.StartTime)
}
Outputs:
2016-01-27 21:56:47.729019925 +0800 CST
Files directory structure:
folder
main.go
dif
dif.go
It works!
Instead of putting int( )
, put float( )
which will let you use decimals along with integers.
I would use FMOD to do this for your game. It has the ability to play any file mostly for sounds and is pretty simple to implement in C++. using FMOD and Dir3ect X together can be powerful and not that difficult. If you are familiar with Singleton classes I would create a Singleton class of a sound manager in your win main cpp and then have access to it whenever to load or play new music or sound effects. here's an audio manager example
#pragma once
#ifndef H_AUDIOMANAGER
#define H_AUDIOMANAGER
#include <string>
#include <Windows.h>
#include "fmod.h"
#include "fmod.hpp"
#include "fmod_codec.h"
#include "fmod_dsp.h"
#include "fmod_errors.h"
#include "fmod_memoryinfo.h"
#include "fmod_output.h"
class AudioManager
{
public:
// Destructor
~AudioManager(void);
void Initialize(void); // Initialize sound components
void Shutdown(void); // Shutdown sound components
// Singleton instance manip methods
static AudioManager* GetInstance(void);
static void DestroyInstance(void);
// Accessors
FMOD::System* GetSystem(void)
{return soundSystem;}
// Sound playing
void Play(FMOD::Sound* sound); // Play a sound/music with default channel
void PlaySFX(FMOD::Sound* sound); // Play a sound effect with custom channel
void PlayBGM(FMOD::Sound* sound); // Play background music with custom channel
// Volume adjustment methods
void SetBGMVolume(float volume);
void SetSFXVolume(float volume);
private:
static AudioManager* instance; // Singleton instance
AudioManager(void); // Constructor
FMOD::System* soundSystem; // Sound system object
FMOD_RESULT result;
FMOD::Channel* bgmChannel; // Channel for background music
static const int numSfxChannels = 4;
FMOD::Channel* sfxChannels[numSfxChannels]; // Channel for sound effects
};
#endif
Performance wise substring(0, 1)
is better as found by following:
String example = "something";
String firstLetter = "";
long l=System.nanoTime();
firstLetter = String.valueOf(example.charAt(0));
System.out.println("String.valueOf: "+ (System.nanoTime()-l));
l=System.nanoTime();
firstLetter = Character.toString(example.charAt(0));
System.out.println("Character.toString: "+ (System.nanoTime()-l));
l=System.nanoTime();
firstLetter = example.substring(0, 1);
System.out.println("substring: "+ (System.nanoTime()-l));
Output:
String.valueOf: 38553
Character.toString: 30451
substring: 8660