Source: java-implementation-of-rubys-gsub
Usage:
// Rewrite an ancient unit of length in SI units.
String result = new Rewriter("([0-9]+(\\.[0-9]+)?)[- ]?(inch(es)?)") {
public String replacement() {
float inches = Float.parseFloat(group(1));
return Float.toString(2.54f * inches) + " cm";
}
}.rewrite("a 17 inch display");
System.out.println(result);
// The "Searching and Replacing with Non-Constant Values Using a
// Regular Expression" example from the Java Almanac.
result = new Rewriter("([a-zA-Z]+[0-9]+)") {
public String replacement() {
return group(1).toUpperCase();
}
}.rewrite("ab12 cd efg34");
System.out.println(result);
Implementation (redesigned):
import static java.lang.String.format;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public abstract class Rewriter {
private Pattern pattern;
private Matcher matcher;
public Rewriter(String regularExpression) {
this.pattern = Pattern.compile(regularExpression);
}
public String group(int i) {
return matcher.group(i);
}
public abstract String replacement() throws Exception;
public String rewrite(CharSequence original) {
return rewrite(original, new StringBuffer(original.length())).toString();
}
public StringBuffer rewrite(CharSequence original, StringBuffer destination) {
try {
this.matcher = pattern.matcher(original);
while (matcher.find()) {
matcher.appendReplacement(destination, "");
destination.append(replacement());
}
matcher.appendTail(destination);
return destination;
} catch (Exception e) {
throw new RuntimeException("Cannot rewrite " + toString(), e);
}
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(pattern.pattern());
for (int i = 0; i <= matcher.groupCount(); i++)
sb.append(format("\n\t(%s) - %s", i, group(i)));
return sb.toString();
}
}
2019
Tools -> Options --> Environment -> Fonts and Colors:
Here's a method that doesn't use ArrayList. The user specifies the size and you can add a do-while loop for recursion.
import java.util.Scanner;
public class Dynamic {
public static Scanner value;
public static void main(String[]args){
value=new Scanner(System.in);
System.out.println("Enter the number of tests to calculate average\n");
int limit=value.nextInt();
int index=0;
int [] marks=new int[limit];
float sum,ave;
sum=0;
while(index<limit)
{
int test=index+1;
System.out.println("Enter the marks on test " +test);
marks[index]=value.nextInt();
sum+=marks[index];
index++;
}
ave=sum/limit;
System.out.println("The average is: " + ave);
}
}
This little example shows how the $rootScope
emit a event that will be listen by a children scope in another controller.
(function(){
angular
.module('ExampleApp',[]);
angular
.module('ExampleApp')
.controller('ExampleController1', Controller1);
Controller1.$inject = ['$rootScope'];
function Controller1($rootScope) {
var vm = this,
message = 'Hi my children scope boy';
vm.sayHi = sayHi;
function sayHi(){
$rootScope.$broadcast('greeting', message);
}
}
angular
.module('ExampleApp')
.controller('ExampleController2', Controller2);
Controller2.$inject = ['$scope'];
function Controller2($scope) {
var vm = this;
$scope.$on('greeting', listenGreeting)
function listenGreeting($event, message){
alert(['Message received',message].join(' : '));
}
}
})();
http://codepen.io/gpincheiraa/pen/xOZwqa
The answer of @gayathri bottom explain technically the differences of all those methods in the scope angular concept and their implementations $scope
and $rootScope
.
Add the following code to your Startup.Auth.cs file under the static constructor:
UserManagerFactory = () => new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId, UserManagerFactory),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
AllowInsecureHttp = true
};
The UserManagerFactory setting line of code is what you use to associate your custom DataContext with the UserManager. Once you have done that, then you can get an instance of the UserManager in your ApiController and the UserManager.UpdateAsync(user) method will work because it is using your DataContext to save the extra properties you've added to your custom application user.
Your array.xml is not right. change it to like this
Here is array.xml file
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="testArray">
<item>first</item>
<item>second</item>
<item>third</item>
<item>fourth</item>
<item>fifth</item>
</string-array>
</resources>
I am too late, but you can try this approach as well.
#include <stdio.h>
#include <stdlib.h>
int main() {
int i=0, j=0, arr[100];
char temp;
while(scanf("%d%c", &arr[i], &temp)){
i++;
if(temp=='\n'){
break;
}
}
for(j=0; j<i; j++) {
printf("%d ", arr[j]);
}
return 0;
}
There are 2 inputs you might have and you can also convert between them.
example: [{"":{"...
The pd.DataFrame() needs a listOfDictionaries as input.
example: '{"":{"...
If you have jsonStr, you need an extra step to listOfDictionaries first. This is obvious as it is generated like:
jsonStr = json.dumps(listOfDictionaries)
Thus, switch back from jsonStr to listOfDictionaries first:
listOfDictionaries = json.loads(jsonStr)
Use git fetch
to fetch all latest created branches.
The -expandproperty does not work with more than 1 object. You can use this one :
Select-Object Name | ForEach-Object {$_.Name}
If there is more than one value then :
Select-Object Name, Country | ForEach-Object {$_.Name + " " + $Country}
It's possible using the button
element.
<button name="name" value="value" type="submit">Sök</button>
From the W3C page on button
:
Buttons created with the BUTTON element function just like buttons created with the INPUT element, but they offer richer rendering possibilities: the BUTTON element may have content.
As Service is already a Context itself
you can even get it through:
Context mContext = this;
OR
Context mContext = [class name].this; //[] only specify the class name
// mContext = JobServiceSchedule.this;
You can use the functions in Python's built-in signal module to set up signal handlers in python. Specifically the signal.signal(signalnum, handler)
function is used to register the handler
function for signal signalnum
.
You can also press =
while less
is open to just display (at the bottom of the screen) information about the current screen, including line numbers, with format:
myfile.txt lines 20530-20585/1816468 byte 1098945/116097872 1% (press RETURN)
So here for example, the screen was currently showing lines 20530-20585
, and the files has a total of 1816468
lines.
This relates to Cristóvão D. Sousa's answer, but I couldn't comment yet.
A straight-forward way of using the flush
keyword argument of Python 3 in order to always have unbuffered output is:
import functools
print = functools.partial(print, flush=True)
afterwards, print will always flush the output directly (except flush=False
is given).
Note, (a) that this answers the question only partially as it doesn't redirect all the output. But I guess print
is the most common way for creating output to stdout
/stderr
in python, so these 2 lines cover probably most of the use cases.
Note (b) that it only works in the module/script where you defined it. This can be good when writing a module as it doesn't mess with the sys.stdout
.
Python 2 doesn't provide the flush
argument, but you could emulate a Python 3-type print
function as described here https://stackoverflow.com/a/27991478/3734258 .
You need to change project settings. Right click your project, go to properites. In Application tab change output type to class library instead of Windows application.
Have you tried DevDefined.OAuth?
I have used it to secure my WebApi with 2-Legged OAuth. I have also successfully tested it with PHP clients.
It's quite easy to add support for OAuth using this library. Here's how you can implement the provider for ASP.NET MVC Web API:
1) Get the source code of DevDefined.OAuth: https://github.com/bittercoder/DevDefined.OAuth - the newest version allows for OAuthContextBuilder
extensibility.
2) Build the library and reference it in your Web API project.
3) Create a custom context builder to support building a context from HttpRequestMessage
:
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net.Http;
using System.Web;
using DevDefined.OAuth.Framework;
public class WebApiOAuthContextBuilder : OAuthContextBuilder
{
public WebApiOAuthContextBuilder()
: base(UriAdjuster)
{
}
public IOAuthContext FromHttpRequest(HttpRequestMessage request)
{
var context = new OAuthContext
{
RawUri = this.CleanUri(request.RequestUri),
Cookies = this.CollectCookies(request),
Headers = ExtractHeaders(request),
RequestMethod = request.Method.ToString(),
QueryParameters = request.GetQueryNameValuePairs()
.ToNameValueCollection(),
};
if (request.Content != null)
{
var contentResult = request.Content.ReadAsByteArrayAsync();
context.RawContent = contentResult.Result;
try
{
// the following line can result in a NullReferenceException
var contentType =
request.Content.Headers.ContentType.MediaType;
context.RawContentType = contentType;
if (contentType.ToLower()
.Contains("application/x-www-form-urlencoded"))
{
var stringContentResult = request.Content
.ReadAsStringAsync();
context.FormEncodedParameters =
HttpUtility.ParseQueryString(stringContentResult.Result);
}
}
catch (NullReferenceException)
{
}
}
this.ParseAuthorizationHeader(context.Headers, context);
return context;
}
protected static NameValueCollection ExtractHeaders(
HttpRequestMessage request)
{
var result = new NameValueCollection();
foreach (var header in request.Headers)
{
var values = header.Value.ToArray();
var value = string.Empty;
if (values.Length > 0)
{
value = values[0];
}
result.Add(header.Key, value);
}
return result;
}
protected NameValueCollection CollectCookies(
HttpRequestMessage request)
{
IEnumerable<string> values;
if (!request.Headers.TryGetValues("Set-Cookie", out values))
{
return new NameValueCollection();
}
var header = values.FirstOrDefault();
return this.CollectCookiesFromHeaderString(header);
}
/// <summary>
/// Adjust the URI to match the RFC specification (no query string!!).
/// </summary>
/// <param name="uri">
/// The original URI.
/// </param>
/// <returns>
/// The adjusted URI.
/// </returns>
private static Uri UriAdjuster(Uri uri)
{
return
new Uri(
string.Format(
"{0}://{1}{2}{3}",
uri.Scheme,
uri.Host,
uri.IsDefaultPort ?
string.Empty :
string.Format(":{0}", uri.Port),
uri.AbsolutePath));
}
}
4) Use this tutorial for creating an OAuth provider: http://code.google.com/p/devdefined-tools/wiki/OAuthProvider. In the last step (Accessing Protected Resource Example) you can use this code in your AuthorizationFilterAttribute
attribute:
public override void OnAuthorization(HttpActionContext actionContext)
{
// the only change I made is use the custom context builder from step 3:
OAuthContext context =
new WebApiOAuthContextBuilder().FromHttpRequest(actionContext.Request);
try
{
provider.AccessProtectedResourceRequest(context);
// do nothing here
}
catch (OAuthException authEx)
{
// the OAuthException's Report property is of the type "OAuthProblemReport", it's ToString()
// implementation is overloaded to return a problem report string as per
// the error reporting OAuth extension: http://wiki.oauth.net/ProblemReporting
actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
{
RequestMessage = request, ReasonPhrase = authEx.Report.ToString()
};
}
}
I have implemented my own provider so I haven't tested the above code (except of course the WebApiOAuthContextBuilder
which I'm using in my provider) but it should work fine.
The most popular way to manage python packages (if you're not using your system package manager) is to use setuptools and easy_install. It is probably already installed on your system. Use it like this:
easy_install django
easy_install uses the Python Package Index which is an amazing resource for python developers. Have a look around to see what packages are available.
A better option is pip, which is gaining traction, as it attempts to fix a lot of the problems associated with easy_install. Pip uses the same package repository as easy_install, it just works better. Really the only time use need to use easy_install is for this command:
easy_install pip
After that, use:
pip install django
At some point you will probably want to learn a bit about virtualenv. If you do a lot of python development on projects with conflicting package requirements, virtualenv is a godsend. It will allow you to have completely different versions of various packages, and switch between them easily depending your needs.
Regarding which python to use, sticking with Apple's python will give you the least headaches, but If you need a newer version (Leopard is 2.5.1 I believe), I would go with the macports python 2.6.
This should do it:
^/\b([a-z0-9]+)\b(?<!ignoreme|ignoreme2|ignoreme3)
You can add as much ignored words as you like, here is a simple PHP implementation:
$ignoredWords = array('ignoreme', 'ignoreme2', 'ignoreme...');
preg_match('~^/\b([a-z0-9]+)\b(?<!' . implode('|', array_map('preg_quote', $ignoredWords)) . ')~i', $string);
for MS excel 2000 office version, click on the pivot table you will find a tab above the ribon, called Pivottable tool - click on that You can change data source from Data tab
Error:Unable to start the daemon process.
This problem might be caused by incorrect configuration of the daemon. For example, an unrecognized JVM option is used.
Please refer to the user guide chapter on the daemon at https://docs.gradle.org/3.3/userguide/gradle_daemon.html
For macOS/OS X, you can use the subprocess module and call 'cls' from the shell:
import subprocess as sp
sp.call('cls', shell=True)
To prevent '0' from showing on top of the window, replace the 2nd line with:
tmp = sp.call('cls', shell=True)
For Linux, you must replace cls
command with clear
tmp = sp.call('clear', shell=True)
check the following link https://www.geeksforgeeks.org/how-to-create-an-unordered_map-of-user-defined-class-in-cpp/ for more details.
I have a crossplatform solution without any additional modules. I was looking for something like a try catch block I could use both in the cmd.exe and in the bash.
The solution is command1 || command2
which seems to work in both enviroments same. So the solution for the OP is:
"scripts": {
"start-watch": "nodemon run-babel index.js",
"wp-server": "webpack-dev-server",
// first command is for the cmd.exe, second one is for the bash
"dev": "(start npm run start-watch && start npm run wp-server) || (npm run start-watch & npm run wp-server)",
"start": "npm run dev"
}
Then simple npm start
(and npm run dev
) will work on all platforms!
TypeScript has Map. You can use like:
public myMap = new Map<K,V>([
[k1, v1],
[k2, v2]
]);
myMap.get(key); // returns value
myMap.set(key, value); // import a new data
myMap.has(key); // check data
In my opinion, it is a fail in the Java syntax design. Polymorphism shouldn't limit the usage of exception handling. In fact, other computer languages don't do it (C#).
Moreover, a method is overriden in a more specialiced subclass so that it is more complex and, for this reason, more probable to throwing new exceptions.
Here is an easy and convenient way of using something similar to the Java map:
var map= {
'map_name_1': map_value_1,
'map_name_2': map_value_2,
'map_name_3': map_value_3,
'map_name_4': map_value_4
}
And to get the value:
alert( map['map_name_1'] ); // fives the value of map_value_1
...... etc .....
I was looking for this, but my example was to take a number, such as 4.2769 and drop it in a span as just 4.3. Not exactly the same, but if this helps:
Model.Statistics.AverageReview <= it's just a double from the model
Then:
@Model.Statistics.AverageReview.ToString("n1") <=gives me 4.3
@Model.Statistics.AverageReview.ToString("n2") <=gives me 4.28
etc...
First, get Pdftk:
sudo apt-get install pdftk
Now, as shown on example page, use
pdftk 1.pdf 2.pdf 3.pdf cat output 123.pdf
for merging pdf files into one.
Steps (1) Just Select your range, rows or column or array , (2) Press ctrl+H , (3 a) then in the find type a space (3 b) in the replace do not enter anything, (4)then just click on replace all..... you are done.
You have two ways to enable it.
First, you can set the absolute path of the php module file in your httpd.conf file like this:
LoadModule php5_module /path/to/mods-available/libphp5.so
Second, you can link the module file to the mods-enabled directory:
ln -s /path/to/mods-available/libphp5.so /path/to/mods-enabled/libphp5.so
You can also use functions with $filter('filter')
:
var foo = $filter('filter')($scope.results.subjects, function (item) {
return item.grade !== 'A';
});
I had this problem and changing Extended Properties to HTML Import fixed it as per this post by Marcus Miris:
strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & importedFilePathAndName _
& ";Extended Properties=""HTML Import;HDR=No;IMEX=1"";"
Another solution is to search for mvc in nuget (right click on your MVC project in visual studio and select "Manage Nuget Packages").
When just a single result is needed, then no loop should be used. Just fetch the row right away.
In case you need to fetch the entire row into associative array:
$row = $result->fetch_assoc();
in case you need just a single value
$row = $result->fetch_row();
$value = $row[0] ?? false;
The last example will return the first column from the first returned row, or false
if no row was returned. It can be also shortened to a single line,
$value = $result->fetch_row()[0] ?? false;
Below are complete examples for different use cases
When variables are to be used in the query, then a prepared statement must be used. For example, given we have a variable $id
:
$query = "SELECT ssfullname, ssemail FROM userss WHERE ud=?";
$stmt = $conn->prepare($query);
$stmt->bind_param("s", $id);
$stmt->execute()
$result = $stmt->get_result();
$row = $result->fetch_assoc();
// in case you need just a single value
$query = "SELECT count(*) FROM userss WHERE id=?";
$stmt = $conn->prepare($query);
$stmt->bind_param("s", $id);
$stmt->execute()
$result = $stmt->get_result();
$value = $result->fetch_row()[0] ?? false;
The detailed explanation of the above process can be found in my article. As to why you must follow it is explained in this famous question
In your case, where no variables to be used in the query, you can use the query()
method:
$query = "SELECT ssfullname, ssemail FROM userss ORDER BY ssid";
$result = $conn->query($query);
// in case you need an array
$row = $result->fetch_assoc();
// OR in case you need just a single value
$value = $result->fetch_row()[0] ?? false;
By the way, although using raw API while learning is okay, consider using some database abstraction library or at least a helper function in the future:
// using a helper function
$sql = "SELECT email FROM users WHERE id=?";
$value = prepared_select($conn, $sql, [$id])->fetch_row[0] ?? false;
// using a database helper class
$email = $db->getCol("SELECT email FROM users WHERE id=?", [$id]);
As you can see, although a helper function can reduce the amount of code, a class' method could encapsulate all the repetitive code inside, making you to write only meaningful parts - the query, the input parameters and the desired result format (in the form of the method's name).
I had similar problem when importing phone number data from excel to mysql database. So a simple trick without the need to identify the length of the phone number (because the length of the phone numbers varied in my data):
UPDATE table SET phone_num = concat('0', phone_num)
I just concated 0 in front of the phone_num
.
You need the get the values from the query string (since you dont have a method set, your using GET by default)
use the following tutorial.
http://papermashup.com/read-url-get-variables-withjavascript/
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
Another option would be to check the error code generated using try-catch block and first catching a WebException.
In my case, the error code was "SendFailure" because of certificate issue on HTTPS url, once I hit HTTP, that got resolved.
You are getting confused with transclude: true
, which would append the inner content.
replace: true
means that the content of the directive template will replace the element that the directive is declared on, in this case the <div myd1>
tag.
http://plnkr.co/edit/k9qSx15fhSZRMwgAIMP4?p=preview
For example without replace:true
<div myd1><span class="replaced" myd1="">directive template1</span></div>
and with replace:true
<span class="replaced" myd1="">directive template1</span>
As you can see in the latter example, the div tag is indeed replaced.
From here:
The
versionKey
is a property set on each document when first created by Mongoose. This keys value contains the internal revision of the document. The name of this document property is configurable. The default is__v
.If this conflicts with your application you can configure as such:
new Schema({..}, { versionKey: '_somethingElse' })
This link will help you in understanding pass by reference in C#. Basically,when an object of reference type is passed by value to an method, only methods which are available on that object can modify the contents of object.
For example List.sort() method changes List contents but if you assign some other object to same variable, that assignment is local to that method. That is why myList remains unchanged.
If we pass object of reference type by using ref keyword then we can assign some other object to same variable and that changes entire object itself.
(Edit: this is the updated version of the documentation linked above.)
<div class="row" style="padding-left:21px;">
<ul class="nav nav-tabs" style="padding-left:40px;">
<li class="active filter"><a href="#month" onclick="Data(this)">This Month</a></li>
<li class="filter"><a href="#year" onclick="Data(this)">Year</a></li>
<li class="filter"><a href="#last60" onclick="Data(this)">60 Days</a></li>
<li class="filter"><a href="#last90" onclick="Data(this)">90 Days</a></li>
</ul>
</div>
<script>
function Data(element)
{
element.removeClass('active');
element.addClass('active') ;
}
</script>
You should look here: https://stackoverflow.com/questions/159025/jquery-grid-recommendations
Update
The link above takes to a question that was closed and then deleted. Here are the original suggestions that were on the most voted answer:
jQuery's .contents() method method allows us to search through the immediate children of the element in the DOM tree.
jQuery:
$('iframe').height( $('iframe').contents().outerHeight() );
Remember that the body of the page inner the iframe must have its height
CSS:
body {
height: auto;
overflow: auto
}
new Buffer(number) // Old
Buffer.alloc(number) // New
new Buffer(string) // Old
Buffer.from(string) // New
new Buffer(string, encoding) // Old
Buffer.from(string, encoding) // New
new Buffer(...arguments) // Old
Buffer.from(...arguments) // New
Note that Buffer.alloc() is also faster on the current Node.js versions than new Buffer(size).fill(0), which is what you would otherwise need to ensure zero-filling.
Given an array you can use the Array.ConvertAll
method:
int[] myInts = Array.ConvertAll(arr, s => int.Parse(s));
Thanks to Marc Gravell for pointing out that the lambda can be omitted, yielding a shorter version shown below:
int[] myInts = Array.ConvertAll(arr, int.Parse);
A LINQ solution is similar, except you would need the extra ToArray
call to get an array:
int[] myInts = arr.Select(int.Parse).ToArray();
It is called as String Interpolation. It is way of creating NEW string with CONSTANTS, VARIABLE, LITERALS and EXPRESSIONS. for examples:
let price = 3
let staringValue = "The price of \(price) mangoes is equal to \(price*price) "
also
let string1 = "anil"
let string2 = "gupta"
let fullName = string1 + string2 // fullName is equal to "anilgupta"
or
let fullName = "\(string1)\(string2)" // fullName is equal to "anilgupta"
it also mean as concatenating string values.
Hope this helps you.
getArguments()
setArguments()
methods seem very useful when it comes to instantiating a Fragment using a static method.
ieMyfragment.createInstance(String msg)
How to do it?
Fragment code
public MyFragment extends Fragment {
private String displayMsg;
private TextView text;
public static MyFragment createInstance(String displayMsg)
{
MyFragment fragment = new MyFragment();
Bundle args = new Bundle();
args.setString("KEY",displayMsg);
fragment.setArguments(args); //set
return fragment;
}
@Override
public void onCreate(Bundle bundle)
{
displayMsg = getArguments().getString("KEY"): // get
}
@Override
public View onCreateView(LayoutInlater inflater, ViewGroup parent, Bundle bundle){
View view = inflater.inflate(R.id.placeholder,parent,false);
text = (TextView)view.findViewById(R.id.myTextView);
text.setText(displayMsg) // show msg
returm view;
}
}
Let's say you want to pass a String while creating an Instance. This is how you will do it.
MyFragment.createInstance("This String will be shown in textView");
1) Why Myfragment.getInstance(String msg) is preferred over new MyFragment(String msg)?
2) Sample code on Fragments
Simula, C++, and C#, which use static method binding by default, the programmer can specify that particular methods should use dynamic binding by labeling them as virtual. Dynamic method binding is central to object-oriented programming.
Object oriented programming requires three fundamental concepts: encapsulation, inheritance, and dynamic method binding.
Encapsulation allows the implementation details of an abstraction to be hidden behind a simple interface.
Inheritance allows a new abstraction to be defined as an extension or refinement of some existing abstraction, obtaining some or all of its characteristics automatically.
Dynamic method binding allows the new abstraction to display its new behavior even when used in a context that expects the old abstraction.
If your base class is called Base
, and your function is called FooBar()
you can call it directly using Base::FooBar()
void Base::FooBar()
{
printf("in Base\n");
}
void ChildOfBase::FooBar()
{
Base::FooBar();
}
Specify bash instead of sh when running the script. I personally noticed they are different under ubuntu 12.10:
bash script.sh arg0 ... argn
Say I want to import data into a component from src/mylib.js
:
var test = {
foo () { console.log('foo') },
bar () { console.log('bar') },
baz () { console.log('baz') }
}
export default test
In my .Vue file I simply imported test
from src/mylib.js
:
<script>
import test from '@/mylib'
console.log(test.foo())
...
</script>
If you're unlucky enough to be switching back and forth from a network behind a proxy and a network NOT behind a proxy, you may have forgotten that your NPM config is set to expect a proxy.
For me, I had to open up ~/.npmrc and comment out my proxy settings (while at home) and vice versa while at work (behind the proxy).
using System;
using System.IO.Ports;
using System.Threading;
namespace SerialReadTest
{
class SerialRead
{
static void Main(string[] args)
{
Console.WriteLine("Serial read init");
SerialPort port = new SerialPort("COM6", 115200, Parity.None, 8, StopBits.One);
port.Open();
while(true){
Console.WriteLine(port.ReadLine());
}
}
}
}
HttpParams is intended to be immutable. The set
and append
methods don't modify the existing instance. Instead they return new instances, with the changes applied.
let params = new HttpParams().set('aaa', 'A'); // now it has aaa
params = params.set('bbb', 'B'); // now it has both
This approach works well with method chaining:
const params = new HttpParams()
.set('one', '1')
.set('two', '2');
...though that might be awkward if you need to wrap any of them in conditions.
Your loop works because you're grabbing a reference to the returned new instance. The code you posted that doesn't work, doesn't. It just calls set() but doesn't grab the result.
let httpParams = new HttpParams().set('aaa', '111'); // now it has aaa
httpParams.set('bbb', '222'); // result has both but is discarded
' \r ' means carriage return.
The \r means nothing special as a consequence.For character-mode terminals (typically emulating even-older printing ones as above), in raw mode, \r and \n act similarly (except both in terms of the cursor, as there is no carriage or roller . Historically a \n was used to move the carriage down, while the \r was used to move the carriage back to the left side of the screen.
You will only see the difference if you have ties within a partition for a particular ordering value.
RANK
and DENSE_RANK
are deterministic in this case, all rows with the same value for both the ordering and partitioning columns will end up with an equal result, whereas ROW_NUMBER
will arbitrarily (non deterministically) assign an incrementing result to the tied rows.
Example: (All rows have the same StyleID
so are in the same partition and within that partition the first 3 rows are tied when ordered by ID
)
WITH T(StyleID, ID)
AS (SELECT 1,1 UNION ALL
SELECT 1,1 UNION ALL
SELECT 1,1 UNION ALL
SELECT 1,2)
SELECT *,
RANK() OVER(PARTITION BY StyleID ORDER BY ID) AS 'RANK',
ROW_NUMBER() OVER(PARTITION BY StyleID ORDER BY ID) AS 'ROW_NUMBER',
DENSE_RANK() OVER(PARTITION BY StyleID ORDER BY ID) AS 'DENSE_RANK'
FROM T
Returns
StyleID ID RANK ROW_NUMBER DENSE_RANK
----------- -------- --------- --------------- ----------
1 1 1 1 1
1 1 1 2 1
1 1 1 3 1
1 2 4 4 2
You can see that for the three identical rows the ROW_NUMBER
increments, the RANK
value remains the same then it leaps to 4
. DENSE_RANK
also assigns the same rank to all three rows but then the next distinct value is assigned a value of 2.
There are several native solutions I've found while searching the way to check network operator.
For API >=17:
TelephonyManager manager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
// Get information about all radio modules on device board
// and check what you need by calling #getCellIdentity.
final List<CellInfo> allCellInfo = manager.getAllCellInfo();
for (CellInfo cellInfo : allCellInfo) {
if (cellInfo instanceof CellInfoGsm) {
CellIdentityGsm cellIdentity = ((CellInfoGsm) cellInfo).getCellIdentity();
//TODO Use cellIdentity to check MCC/MNC code, for instance.
} else if (cellInfo instanceof CellInfoWcdma) {
CellIdentityWcdma cellIdentity = ((CellInfoWcdma) cellInfo).getCellIdentity();
} else if (cellInfo instanceof CellInfoLte) {
CellIdentityLte cellIdentity = ((CellInfoLte) cellInfo).getCellIdentity();
} else if (cellInfo instanceof CellInfoCdma) {
CellIdentityCdma cellIdentity = ((CellInfoCdma) cellInfo).getCellIdentity();
}
}
In AndroidManifest add permission:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
</manifest>
To get network operator you can check mcc and mnc codes:
For API >=22:
final SubscriptionManager subscriptionManager = SubscriptionManager.from(context);
final List<SubscriptionInfo> activeSubscriptionInfoList = subscriptionManager.getActiveSubscriptionInfoList();
for (SubscriptionInfo subscriptionInfo : activeSubscriptionInfoList) {
final CharSequence carrierName = subscriptionInfo.getCarrierName();
final CharSequence displayName = subscriptionInfo.getDisplayName();
final int mcc = subscriptionInfo.getMcc();
final int mnc = subscriptionInfo.getMnc();
final String subscriptionInfoNumber = subscriptionInfo.getNumber();
}
For API >=23. To just check if phone is dual/triple/many sim:
TelephonyManager manager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
if (manager.getPhoneCount() == 2) {
// Dual sim
}
Shameless plug for an open source project I run, but given the lively discussion about which .NET logging framework is more active I thought I'd post an obligatory link to Serilog.
To use within an application, Serilog is similar to (and draws heavily on) log4net. Unlike other .NET logging options, however, Serilog is about preserving the structure of log events for offline analysis. When you write:
Log.Information("The answer is {Answer}", 42);
Most logging libraries immediately render the message into a string. Serilog can do that too, but it preserves the { Answer: 42 }
property so that later on, using one of a number of NoSQL data stores, you can properly query events based on the value of Answer
.
We're close to a 1.0 and support all of the modern (.NET 4.5, Windows Store and Windows Phone 8) platforms.
Sign-off is a requirement for getting patches into the Linux kernel and a few other projects, but most projects don't actually use it.
It was introduced in the wake of the SCO lawsuit, (and other accusations of copyright infringement from SCO, most of which they never actually took to court), as a Developers Certificate of Origin. It is used to say that you certify that you have created the patch in question, or that you certify that to the best of your knowledge, it was created under an appropriate open-source license, or that it has been provided to you by someone else under those terms. This can help establish a chain of people who take responsibility for the copyright status of the code in question, to help ensure that copyrighted code not released under an appropriate free software (open source) license is not included in the kernel.
Also remember one thing. Very important
You have to specify the command something like this to be more precise
grep -l "pattern" *
with open('output.txt', 'r') as f:
lines = f.read().splitlines()
last_line = lines[-1]
print last_line
Replace that line with:
$("#someElement").click(function() {
window.location.href = window.location.href;
});
or:
$("#someElement").click(function() {
window.location.reload();
});
Well, I'm late.
In your image, the paper is white
, while the background is colored
. So, it's better to detect the paper is Saturation(???)
channel in HSV color space
. Take refer to wiki HSL_and_HSV first. Then I'll copy most idea from my answer in this Detect Colored Segment in an image.
BGR
bgr
to hsv
spaceCanny
, or HoughLines
as you like, I choose findContours
), approx to get the corners.This is my result:
The Python code(Python 3.5 + OpenCV 3.3):
#!/usr/bin/python3
# 2017.12.20 10:47:28 CST
# 2017.12.20 11:29:30 CST
import cv2
import numpy as np
##(1) read into bgr-space
img = cv2.imread("test2.jpg")
##(2) convert to hsv-space, then split the channels
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
h,s,v = cv2.split(hsv)
##(3) threshold the S channel using adaptive method(`THRESH_OTSU`) or fixed thresh
th, threshed = cv2.threshold(s, 50, 255, cv2.THRESH_BINARY_INV)
##(4) find all the external contours on the threshed S
#_, cnts, _ = cv2.findContours(threshed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cv2.findContours(threshed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]
canvas = img.copy()
#cv2.drawContours(canvas, cnts, -1, (0,255,0), 1)
## sort and choose the largest contour
cnts = sorted(cnts, key = cv2.contourArea)
cnt = cnts[-1]
## approx the contour, so the get the corner points
arclen = cv2.arcLength(cnt, True)
approx = cv2.approxPolyDP(cnt, 0.02* arclen, True)
cv2.drawContours(canvas, [cnt], -1, (255,0,0), 1, cv2.LINE_AA)
cv2.drawContours(canvas, [approx], -1, (0, 0, 255), 1, cv2.LINE_AA)
## Ok, you can see the result as tag(6)
cv2.imwrite("detected.png", canvas)
Related answers:
In Java you can only import class Names, or static methods/fields.
To import class use
import full.package.name.of.SomeClass;
to import static methods/fields use
import static full.package.name.of.SomeClass.staticMethod;
import static full.package.name.of.SomeClass.staticField;
This is what worked for me:
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
Use callbacks. Something like this should work based on your sample code.
function someFunc() {
callAjaxfunc(function() {
console.log('Pass2');
});
}
function callAjaxfunc(callback) {
//All ajax calls called here
onAjaxSuccess: function() {
callback();
};
console.log('Pass1');
}
This will print Pass1
immediately (assuming ajax request takes atleast a few microseconds), then print Pass2
when the onAjaxSuccess
is executed.
had better be
List
The only List
implementation in java.util.concurrent
is CopyOnWriteArrayList. There's also the option of a synchronized list as Travis Webb mentions.
That said, are you sure you need it to be a List
? There are a lot more options for concurrent Queue
s and Map
s (and you can make Set
s from Map
s), and those structures tend to make the most sense for many of the types of things you want to do with a shared data structure.
For queues, you have a huge number of options and which is most appropriate depends on how you need to use it:
public void showNotification (String from, String notification, Intent intent) {
PendingIntent pendingIntent = PendingIntent.getActivity(
context,
Notification_ID,
intent,
PendingIntent.FLAG_UPDATE_CURRENT
);
String NOTIFICATION_CHANNEL_ID = "my_channel_id_01";
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_DEFAULT);
// Configure the notification channel.
notificationChannel.setDescription("Channel description");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID);
Notification mNotification = builder
.setContentTitle(from)
.setContentText(notification)
// .setTicker("Hearty365")
// .setContentInfo("Info")
// .setPriority(Notification.PRIORITY_MAX)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
// .setDefaults(Notification.DEFAULT_ALL)
// .setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
.build();
notificationManager.notify(/*notification id*/Notification_ID, mNotification);
}
I'm sure you know that a std::vector<X>
stores a whole bunch of X
objects, right? But if you have a std::map<X, Y>
, what it actually stores is a whole bunch of std::pair<const X, Y>
s. That's exactly what a map is - it pairs together the keys and the associated values.
When you iterate over a std::map
, you're iterating over all of these std::pair
s. When you dereference one of these iterators, you get a std::pair
containing the key and its associated value.
std::map<std::string, int> m = /* fill it */;
auto it = m.begin();
Here, if you now do *it
, you will get the the std::pair
for the first element in the map.
Now the type std::pair
gives you access to its elements through two members: first
and second
. So if you have a std::pair<X, Y>
called p
, p.first
is an X
object and p.second
is a Y
object.
So now you know that dereferencing a std::map
iterator gives you a std::pair
, you can then access its elements with first
and second
. For example, (*it).first
will give you the key and (*it).second
will give you the value. These are equivalent to it->first
and it->second
.
"Better" is subjective.
querySelector
is the newer feature.
getElementById
is better supported than querySelector
.
querySelector
is better supported than getElementsByClassName
.
querySelector
lets you find elements with rules that can't be expressed with getElementById
and getElementsByClassName
You need to pick the appropriate tool for any given task.
(In the above, for querySelector
read querySelector
/ querySelectorAll
).
Make two java classes
Zoom class
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
public class Zoom extends View {
private Drawable image;
ImageButton img,img1;
private int zoomControler=20;
public Zoom(Context context){
super(context);
image=context.getResources().getDrawable(R.drawable.j);
//image=context.getResources().getDrawable(R.drawable.icon);
setFocusable(true);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//here u can control the width and height of the images........ this line is very important
image.setBounds((getWidth()/2)-zoomControler, (getHeight()/2)-zoomControler, (getWidth()/2)+zoomControler, (getHeight()/2)+zoomControler);
image.draw(canvas);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode==KeyEvent.KEYCODE_DPAD_UP){
// zoom in
zoomControler+=10;
}
if(keyCode==KeyEvent.KEYCODE_DPAD_DOWN){
// zoom out
zoomControler-=10;
}
if(zoomControler<10){
zoomControler=10;
}
invalidate();
return true;
}
}
make second class
import android.app.Activity;
import android.os.Bundle;
public class Zoomexample extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(new Zoom(this));
}
}
You need to use overflow option like below:
.nav{
max-height: 300px;
overflow-y: scroll;
}
Change the height according to amount of items you need to show
It should be:
SELECT SalesID, COUNT(*)
FROM AXDelNotesNoTracking
GROUP BY SalesID
HAVING COUNT(*) > 1
Regarding your initial query:
Edit:
And I just thought of this, if you want to see WHICH items are in there more than once (but this depends on which database you are using):
;WITH cte AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY SalesID ORDER BY SalesID) AS [Num]
FROM AXDelNotesNoTracking
)
SELECT *
FROM cte
WHERE cte.Num > 1
Of course, this just shows the rows that have appeared with the same SalesID but does not show the initial SalesID value that has appeared more than once. Meaning, if a SalesID shows up 3 times, this query will show instances 2 and 3 but not the first instance. Still, it might help depending on why you are looking for multiple SalesID values.
Edit2:
The following query was posted by APC below and is better than the CTE I mention above in that it shows all rows in which a SalesID has appeared more than once. I am including it here for completeness. I merely added an ORDER BY to keep the SalesID values grouped together. The ORDER BY might also help in the CTE above.
SELECT *
FROM AXDelNotesNoTracking
WHERE SalesID IN
( SELECT SalesID
FROM AXDelNotesNoTracking
GROUP BY SalesID
HAVING COUNT(*) > 1
)
ORDER BY SalesID
There are many correct answers. However, here a One-Liner in PowerShell I use to determine the MSBuild path for the most recent version:
Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\MSBuild\ToolsVersions\' |
Get-ItemProperty -Name MSBuildToolsPath |
Sort-Object PSChildName |
Select-Object -ExpandProperty MSBuildToolsPath -first 1
Generally speaking, you can update your index mapping using the put mapping api (reference here) :
curl -XPUT 'http://localhost:9200/advert_index/_mapping/advert_type' -d '
{
"advert_type" : {
"properties" : {
//your new mapping properties
}
}
}
'
It's especially useful for adding new fields. However, in your case, you will try to change the location type, which will cause a conflict and prevent the new mapping from being used.
You could use the put mapping api to add another property containing the location as a lat/lon array, but you won't be able to update the previous location field itself.
Finally, you will have to reindex your data for your new mapping to be taken into account.
The best solution would really be to create a new index.
If your problem with creating another index is downtime, you should take a look at aliases to make things go smoothly.
This is what I do for those situations:
I don't start the html element with class 'hide', but I put style="display: none".
This is because bootstrap jquery modifies the style attribute and not the classes to hide/unhide.
Example:
<button type="button" id="btn_cancel" class="btn default" style="display: none">Cancel</button>
or
<button type="button" id="btn_cancel" class="btn default display-hide">Cancel</button>
Later on, you can run all the following that will work:
$('#btn_cancel').toggle() // toggle between hide/unhide
$('#btn_cancel').hide()
$('#btn_cancel').show()
You can also uso the class of Twitter Bootstrap 'display-hide', which also works with the jQuery IU .toggle() method.
##If i want to wait for some response from server or any action we use setTimeOut.
functionOne =function(){
console.info("First");
setTimeout(()=>{
console.info("After timeOut 1");
},5000);
console.info("only setTimeOut() inside code waiting..");
}
functionTwo =function(){
console.info("second");
}
functionOne();
functionTwo();
## So here console.info("After timeOut 1"); will be executed after time elapsed.
Output:
*******************************************************************************
First
only setTimeOut() inside code waiting..
second
undefined
After timeOut 1 // executed after time elapsed.
Select *
FROM test_table
WHERE user_id = value
AND date_added = (select max(date_added)
from test_table
where user_id = value)
One more way of convenient placement of Environment.NewLine in format string. The idea is to create string extension method that formats string as usual but also replaces {nl} in text with Environment.NewLine
Usage
" X={0} {nl} Y={1}{nl} X+Y={2}".FormatIt(1, 2, 1+2);
gives:
X=1
Y=2
X+Y=3
Code
///<summary>
/// Use "string".FormatIt(...) instead of string.Format("string, ...)
/// Use {nl} in text to insert Environment.NewLine
///</summary>
///<exception cref="ArgumentNullException">If format is null</exception>
[StringFormatMethod("format")]
public static string FormatIt(this string format, params object[] args)
{
if (format == null) throw new ArgumentNullException("format");
return string.Format(format.Replace("{nl}", Environment.NewLine), args);
}
Note
If you want ReSharper to highlight your parameters, add attribute to the method above
[StringFormatMethod("format")]
This implementation is obviously less efficient than just String.Format
Maybe one, who interested in this question would be interested in the next question too: Named string formatting in C#
See http://www.w3schools.com/tags/att_input_accept.asp:
The accept attribute is supported in all major browsers, except Internet Explorer and Safari. Definition and Usage
The accept attribute specifies the types of files that the server accepts (that can be submitted through a file upload).
Note: The accept attribute can only be used with
<input type="file">
.Tip: Do not use this attribute as a validation tool. File uploads should be validated on the server.
Syntax
<input accept="audio/*|video/*|image/*|MIME_type" />
Tip: To specify more than one value, separate the values with a comma (e.g.
<input accept="audio/*,video/*,image/*" />
.
function arrayColumn(arr, n) {_x000D_
return arr.map(x=> x[n]);_x000D_
}_x000D_
_x000D_
var twoDimensionalArray = [_x000D_
[1, 2, 3],_x000D_
[4, 5, 6],_x000D_
[7, 8, 9]_x000D_
];_x000D_
_x000D_
console.log(arrayColumn(twoDimensionalArray, 1));
_x000D_
Try this - https://github.com/laracasts/PHP-Vars-To-Js-Transformer Is simple way to append PHP variables to Javascript.
In short, its because of recycling the views and using them again!
how can you avoid that :
1.In onBindViewHolder
check whether you should check or uncheck boxes.
don't forget to put both if and else
if (...)
holder.cbSelect.setChecked(true);
else
holder.cbSelect.setChecked(false);
myItems
array ! so whenever a new view is shown, it read the newest statue of the object.If I remember correctly, there is a strict standard limit for the memory usage in V8 of around 1.7 GB, if you do not increase it manually.
In one of our products we followed this solution in our deploy script:
node --max-old-space-size=4096 yourFile.js
There would also be a new space command but as I read here: a-tour-of-v8-garbage-collection the new space only collects the newly created short-term data and the old space contains all referenced data structures which should be in your case the best option.
Here is a good discussion about superclass constructor calling rules. You always want the base class constructor to be called before the derived class constructor in order to form an object properly. Which is why this form is used
B( int v) : A( v )
{
}
<% form_for(@message) do |f| %>
<%= f.radio_button :contactmethod, 'email', :checked => true %>
<%= label :contactmethod_email, 'Email' %>
<%= f.radio_button :contactmethod, 'sms' %>
<%= label :contactmethod_sms, 'SMS' %>
<% end %>
Pidfile contains pid of a process. It is a convention allowing long running processes to be more self-aware. Server process can inspect it to stop itself, or have heuristic that its other instance is already running. Pidfiles can also be used to conventiently kill risk manually, e.g. pkill -F <some.pid>
When you try to access it as $result['context']
, you treating it as an array, the error it's telling you that you are actually dealing with an object, then you should access it as $result->context
Here THIS context is getting changed. Use arrow function to keep context of React class.
VK.init(() => {
console.info("API initialisation successful");
VK.api('users.get',{fields: 'photo_50'},(data) => {
if(data.response){
this.setState({ //the error happens here
FirstName: data.response[0].first_name
});
console.info(this.state.FirstName);
}
});
}, function(){
console.info("API initialisation failed");
}, '5.34');
Here is a way by putting a transparent A element over the table rows. Advantages are:
Disadvantages:
The table stays as is:
<table id="tab1">
<tbody>
<tr>
<td>Blah Blah</td>
<td>1234567</td>
<td>£158,000</td>
</tr>
</tbody>
</table>
Add the links (for each row) via jQuery JavaScript by inserting an A element into each first column and setting the needed properties:
// v1, fixed for IE and Chrome
// v0, worked on Firefox only
// width needed for adjusting the width of the A element
var mywidth=$('#tab1').width();
$('#tab1 tbody>tr>td:nth-child(1)').each(function(index){
$(this).css('position', 'relative');// debug: .css('background-color', '#f11');
// insert the <A> element
var myA=$('<A>');
$(this).append(myA);
var myheight=$(this).height();
myA.css({//"border":'1px solid #2dd', border for debug only
'display': 'block',
'left': '0',
'top': '0',
'position': 'absolute'
})
.attr('href','the link here')
.width(mywidth)
.height(myheight)
;
});
The width and height setting can be tricky, if many paddings and margins are used, but in general a few pixels off should not even matter.
Live demo here: http://jsfiddle.net/qo0dx0oo/ (works in Firefox, but not IE or Chrome, there the link is positioned wrong)
Fixed for Chrome and IE (still works in FF too): http://jsfiddle.net/qo0dx0oo/2/
For Visual Studio 2019
it wasn't working by signing out/ signing in, etc. as mention in other solutions. What simply worked was performing the operation from new branches window/section. i.e,
1. Click on:
2. It opens up the branches section as below. Then right click on desired branch and perform the operation which wasn't working earlier. (for me, it was PUSH that wasn't throwing this error)
(in VS 2019 new Git interface, I usually push/pull/fetch from the small arrows as shown in first screenshot. But sometime they throw error (mentioned in question) and do not allow pushing/pulling. What then what worked was the solution I mentioned above. May be it's a bug or something, but this solution saves you from resetting user data, and mess of signing out/in from multiple accounts, etc.)
Using reduce()
from purrr
is slightly faster than rowSums
and definately faster than apply
, since you avoid iterating over all the rows and just take advantage of the vectorized operations:
library(purrr)
library(dplyr)
iris %>% mutate(Petal = reduce(select(., starts_with("Petal")), `+`))
See this for timings
The solution is actually a lot easier than any of the other suggestions:
std::wstring stemp = std::wstring(s.begin(), s.end());
LPCWSTR sw = stemp.c_str();
Best of all, it's platform independent.
This can be accomplished by Unmarshaling into a map[string]json.RawMessage
.
var objmap map[string]json.RawMessage
err := json.Unmarshal(data, &objmap)
To further parse sendMsg
, you could then do something like:
var s sendMsg
err = json.Unmarshal(objmap["sendMsg"], &s)
For say
, you can do the same thing and unmarshal into a string:
var str string
err = json.Unmarshal(objmap["say"], &str)
EDIT: Keep in mind you will also need to export the variables in your sendMsg struct to unmarshal correctly. So your struct definition would be:
type sendMsg struct {
User string
Msg string
}
Why don't you just use a singleton?
import android.content.Context;
public class ClassicSingleton {
private Context c=null;
private static ClassicSingleton instance = null;
protected ClassicSingleton()
{
// Exists only to defeat instantiation.
}
public void setContext(Context ctx)
{
c=ctx;
}
public Context getContext()
{
return c;
}
public static ClassicSingleton getInstance()
{
if(instance == null) {
instance = new ClassicSingleton();
}
return instance;
}
}
Then in the activity class:
private ClassicSingleton cs = ClassicSingleton.getInstance();
And in the non activity class:
ClassicSingleton cs= ClassicSingleton.getInstance();
Context c=cs.getContext();
ImageView imageView = (ImageView) ((Activity)c).findViewById(R.id.imageView1);
This worked
<video class="video-box" poster="/" controls>
<source src="some source" type="video/mp4">
</video>
And the CSS
.video-box{
background-image: 'some image';
background-size: cover;
}
Whenever we are trying to connect to URL,
if server at the other site is running on https protocol and is mandating that we should communicate via information provided in certificate then we have following option:
1) ask for the certificate(download the certificate), import this certificate in trustore. Default trustore java uses can be found in \Java\jdk1.6.0_29\jre\lib\security\cacerts, then if we retry to connect to the URL connection would be accepted.
2) In normal business cases, we might be connecting to internal URLS in organizations and we know that they are correct. In such cases, you trust that it is the correct URL, In such cases above, code can be used which will not mandate to store the certificate to connect to particular URL.
for the point no 2 we have to follow below steps :
1) write below method which sets HostnameVerifier for HttpsURLConnection which returns true for all cases meaning we are trusting the trustStore.
// trusting all certificate
public void doTrustToCertificates() throws Exception {
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {
return;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {
return;
}
}
};
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
if (!urlHostName.equalsIgnoreCase(session.getPeerHost())) {
System.out.println("Warning: URL host '" + urlHostName + "' is different to SSLSession host '" + session.getPeerHost() + "'.");
}
return true;
}
};
HttpsURLConnection.setDefaultHostnameVerifier(hv);
}
2) write below method, which calls doTrustToCertificates before trying to connect to URL
// connecting to URL
public void connectToUrl(){
doTrustToCertificates();//
URL url = new URL("https://www.example.com");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
System.out.println("ResponseCode ="+conn.getResponseCode());
}
This call will return response code = 200 means connection is successful.
For more detail and sample example you can refer to URL.
See: http://jsfiddle.net/thirtydot/EDp8R/
text-align: justify
combined with .stretch
is what's handling the positioning.display:inline-block; *display:inline; zoom:1
fixes inline-block
for IE6/7, see here.font-size: 0; line-height: 0
fixes a minor issue in IE6.#container {_x000D_
border: 2px dashed #444;_x000D_
height: 125px;_x000D_
text-align: justify;_x000D_
-ms-text-justify: distribute-all-lines;_x000D_
text-justify: distribute-all-lines;_x000D_
/* just for demo */_x000D_
min-width: 612px;_x000D_
}_x000D_
_x000D_
.box1,_x000D_
.box2,_x000D_
.box3,_x000D_
.box4 {_x000D_
width: 150px;_x000D_
height: 125px;_x000D_
vertical-align: top;_x000D_
display: inline-block;_x000D_
*display: inline;_x000D_
zoom: 1_x000D_
}_x000D_
_x000D_
.stretch {_x000D_
width: 100%;_x000D_
display: inline-block;_x000D_
font-size: 0;_x000D_
line-height: 0_x000D_
}_x000D_
_x000D_
.box1,_x000D_
.box3 {_x000D_
background: #ccc_x000D_
}_x000D_
_x000D_
.box2,_x000D_
.box4 {_x000D_
background: #0ff_x000D_
}
_x000D_
<div id="container">_x000D_
<div class="box1"></div>_x000D_
<div class="box2"></div>_x000D_
<div class="box3"></div>_x000D_
<div class="box4"></div>_x000D_
<span class="stretch"></span>_x000D_
</div>
_x000D_
The extra span
(.stretch
) can be replaced with :after
.
This still works in all the same browsers as the above solution. :after
doesn't work in IE6/7, but they're using distribute-all-lines
anyway, so it doesn't matter.
See: http://jsfiddle.net/thirtydot/EDp8R/3/
There's a minor downside to :after
: to make the last row work perfectly in Safari, you have to be careful with the whitespace in the HTML.
Specifically, this doesn't work:
<div id="container">
..
<div class="box3"></div>
<div class="box4"></div>
</div>
And this does:
<div id="container">
..
<div class="box3"></div>
<div class="box4"></div></div>
You can use this for any arbitrary number of child div
s without adding a boxN
class to each one by changing
.box1, .box2, .box3, .box4 { ...
to
#container > div { ...
This selects any div that is the first child of the #container
div, and no others below it. To generalize the background colors, you can use the CSS3 nth-order selector, although it's only supported in IE9+ and other modern browsers:
.box1, .box3 { ...
becomes:
#container > div:nth-child(odd) { ...
See here for a jsfiddle example.
In Python 2, open outfile
with mode 'wb'
instead of 'w'
. The csv.writer
writes \r\n
into the file directly. If you don't open the file in binary mode, it will write \r\r\n
because on Windows text mode will translate each \n
into \r\n
.
In Python 3 the required syntax changed (see documentation links below), so open outfile
with the additional parameter newline=''
(empty string) instead.
# Python 2
with open('/pythonwork/thefile_subset11.csv', 'wb') as outfile:
writer = csv.writer(outfile)
# Python 3
with open('/pythonwork/thefile_subset11.csv', 'w', newline='') as outfile:
writer = csv.writer(outfile)
decimal has a smaller range, but greater precision - so you don't lose all those pennies over time!
Full details here:
We use maven2 in all our projects and it speeds up development tenfold (combined with a nice continuous integration platform).
The only feature of maven2 that has caused us a lot of headaches in the past is the transitive dependency mechanism. In a Utopian world it would be the end-all solution to all dependency issues but in practice it tends to send you straight to dependency hell.
Our main problem came from the fact that various components in the default maven2 repository depend on different versions of the same library (i.e component1 and component2 both require a logging framework but component1 requires v1 and component2 requires v2).
To solve this we simply have our own local repository containing all the libraries we need. This allows us to ensure that all libraries we use that have their own dependencies depend on the same versions of other libraries.
<span style="color:orange;">orange text</span>
Is the only way I know of barring the font tag.
No one mentioned .env
in here yet? Make a .env
file in your app root, then require('dotenv').config()
and read the values. Easily changed, easily read, cross platform.
It looks like you want to define Truck as a Class
with properties NumberOfAxles, AxleWeights & AxleSpacings.
This can be defined in a CLASS MODULE (here named clsTrucks)
Option Explicit
Private tID As String
Private tNumberOfAxles As Double
Private tAxleSpacings As Double
Public Property Get truckID() As String
truckID = tID
End Property
Public Property Let truckID(value As String)
tID = value
End Property
Public Property Get truckNumberOfAxles() As Double
truckNumberOfAxles = tNumberOfAxles
End Property
Public Property Let truckNumberOfAxles(value As Double)
tNumberOfAxles = value
End Property
Public Property Get truckAxleSpacings() As Double
truckAxleSpacings = tAxleSpacings
End Property
Public Property Let truckAxleSpacings(value As Double)
tAxleSpacings = value
End Property
then in a MODULE the following defines a new truck and it's properties and adds it to a collection of trucks and then retrieves the collection.
Option Explicit
Public TruckCollection As New Collection
Sub DefineNewTruck()
Dim tempTruck As clsTrucks
Dim i As Long
'Add 5 trucks
For i = 1 To 5
Set tempTruck = New clsTrucks
'Random data
tempTruck.truckID = "Truck" & i
tempTruck.truckAxleSpacings = 13.5 + i
tempTruck.truckNumberOfAxles = 20.5 + i
'tempTruck.truckID is the collection key
TruckCollection.Add tempTruck, tempTruck.truckID
Next i
'retrieve 5 trucks
For i = 1 To 5
'retrieve by collection index
Debug.Print TruckCollection(i).truckAxleSpacings
'retrieve by key
Debug.Print TruckCollection("Truck" & i).truckAxleSpacings
Next i
End Sub
There are several ways of doing this so it really depends on how you intend to use the data as to whether an a class/collection is the best setup or arrays/dictionaries etc.
just use This
public ActionResult LoadCountries()
{
List<SelectListItem> li = new List<SelectListItem>();
li.Add(new SelectListItem { Text = "Select", Value = "0" });
li.Add(new SelectListItem { Text = "India", Value = "1" });
li.Add(new SelectListItem { Text = "Srilanka", Value = "2" });
li.Add(new SelectListItem { Text = "China", Value = "3" });
li.Add(new SelectListItem { Text = "Austrila", Value = "4" });
li.Add(new SelectListItem { Text = "USA", Value = "5" });
li.Add(new SelectListItem { Text = "UK", Value = "6" });
ViewData["country"] = li;
return View();
}
and in View use following.
@Html.DropDownList("Country", ViewData["country"] as List<SelectListItem>)
if you want to get data from Dataset and populate these data in a list box then use following code.
List<SelectListItem> li= new List<SelectListItem>();
for (int rows = 0; rows <= ds.Tables[0].Rows.Count - 1; rows++)
{
li.Add(new SelectListItem { Text = ds.Tables[0].Rows[rows][1].ToString(), Value = ds.Tables[0].Rows[rows][0].ToString() });
}
ViewData["FeedBack"] = li;
return View();
and in view write following code.
@Html.DropDownList("FeedBack", ViewData["FeedBack"] as List<SelectListItem>)
Yes, you can use this query (Instead of 'Specialist'
and 'Developer'
, type any strings you want separated by comma and change employees
table with your table)
SELECT * FROM employees em
WHERE EXISTS (select 1 from table(sys.dbms_debug_vc2coll('Specialist', 'Developer')) mt where em.job like ('%' || mt.column_value || '%'));
Why my query is better than the accepted answer: You don't need a CREATE TABLE
permission to run it. This can be executed with just SELECT
permissions.
The easiest way in plain Java with no dependencies is the following one-liner:
new String(new char[generation]).replace("\0", "-")
Replace generation with number of repetitions, and the "-" with the string (or char) you want repeated.
All this does is create an empty string containing n number of 0x00 characters, and the built-in String#replace method does the rest.
Here's a sample to copy and paste:
public static String repeat(int count, String with) {
return new String(new char[count]).replace("\0", with);
}
public static String repeat(int count) {
return repeat(count, " ");
}
public static void main(String[] args) {
for (int n = 0; n < 10; n++) {
System.out.println(repeat(n) + " Hello");
}
for (int n = 0; n < 10; n++) {
System.out.println(repeat(n, ":-) ") + " Hello");
}
}
Iif you want a particular <canvas id="canvasID">
to be always transparent you just have to set
#canvasID{
opacity:0.5;
}
Instead, if you want some particular elements inside the canvas area to be transparent, you have to set transparency when you draw, i.e.
context.fillStyle = "rgba(0, 0, 200, 0.5)";
Remove the function and check the output of:
var_dump(function_exists('parseDate'));
In which case, change the name of the function.
If you get false, you're including the file with that function twice, replace :
include
by
include_once
And replace :
require
by
require_once
EDIT : I'm just a little too late, post before beat me to it !
SELECT CASE WHEN COUNT(1) > 0 THEN 1 ELSE 0 END AS [Value]
FROM Sites S
WHERE S.Id = @SiteId and S.Status = 1 AND
(S.WebUserId = @WebUserId OR S.AllowUploads = 1)
(function($) {_x000D_
$(document).ready(function() {_x000D_
$('#data').click(function(e) {_x000D_
e.preventDefault();_x000D_
$.each($("#keywords").val().split("\n"), function(e, element) {_x000D_
alert(element);_x000D_
});_x000D_
});_x000D_
});_x000D_
})(jQuery);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<textarea id="keywords">Hello_x000D_
World</textarea>_x000D_
<input id="data" type="button" value="submit">
_x000D_
I found a much simpler alternative way to generating soap message. Given a Person Object:
import com.fasterxml.jackson.annotation.JsonInclude;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Person {
private String name;
private int age;
private String address; //setter and getters below
}
Below is a simple Soap Message Generator:
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
@Slf4j
public class SoapGenerator {
protected static final ObjectMapper XML_MAPPER = new XmlMapper()
.enable(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
.registerModule(new JavaTimeModule());
private static final String SOAP_BODY_OPEN = "<soap:Body>";
private static final String SOAP_BODY_CLOSE = "</soap:Body>";
private static final String SOAP_ENVELOPE_OPEN = "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">";
private static final String SOAP_ENVELOPE_CLOSE = "</soap:Envelope>";
public static String soapWrap(String xml) {
return SOAP_ENVELOPE_OPEN + SOAP_BODY_OPEN + xml + SOAP_BODY_CLOSE + SOAP_ENVELOPE_CLOSE;
}
public static String soapUnwrap(String xml) {
return StringUtils.substringBetween(xml, SOAP_BODY_OPEN, SOAP_BODY_CLOSE);
}
}
You can use by:
public static void main(String[] args) throws Exception{
Person p = new Person();
p.setName("Test");
p.setAge(12);
String xml = SoapGenerator.soapWrap(XML_MAPPER.writeValueAsString(p));
log.info("Generated String");
log.info(xml);
}
Here is a simple way to implement ls
command using c
. To run use for example ./xls /tmp
#include<stdio.h>
#include <dirent.h>
void main(int argc,char *argv[])
{
DIR *dir;
struct dirent *dent;
dir = opendir(argv[1]);
if(dir!=NULL)
{
while((dent=readdir(dir))!=NULL)
{
if((strcmp(dent->d_name,".")==0 || strcmp(dent->d_name,"..")==0 || (*dent->d_name) == '.' ))
{
}
else
{
printf(dent->d_name);
printf("\n");
}
}
}
close(dir);
}
Was getting Illegal mix of collations while creating a category in Bagisto. Running these commands (thank you @Quy Le) solved the issue for me:
--set utf8 for connection
SET collation_connection = 'utf8_general_ci'
--change CHARACTER SET of DB to utf8
ALTER DATABASE dbName CHARACTER SET utf8 COLLATE utf8_general_ci
--change category tables
ALTER TABLE categories CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci
ALTER TABLE category_translations CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci
Save this as *.bat file and see differences
:: print echo command and its output
echo 1
:: does not print echo command just its output
@echo 2
:: print dir command but not its output
dir > null
:: does not print dir command nor its output
@dir c:\ > null
:: does not print echo (and all other commands) but print its output
@echo off
echo 3
@echo on
REM this comment will appear in console if 'echo off' was not set
@set /p pressedKey=Press any key to exit
display: inline-block;
max-width: 80%;
height: 1.5em;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
This might be seen as a little complex but does exactly what you want
SELECT
DISTINCT(p.`ProductID`) AS ProductID,
SUM(pl.CashAmount) AS Cash,
SUM(pr.CashAmount) AS `Check`,
SUM(px.CashAmount) AS `Credit Card`,
SUM(pl.CashAmount) + SUM(pr.CashAmount) +SUM(px.CashAmount) AS Amount
FROM
`payments` AS p
LEFT JOIN (SELECT ProductID,PaymentMethod , IFNULL(Amount,0) AS CashAmount FROM payments WHERE PaymentMethod = 'Cash' GROUP BY ProductID , PaymentMethod ) AS pl
ON pl.`PaymentMethod` = p.`PaymentMethod` AND pl.ProductID = p.`ProductID`
LEFT JOIN (SELECT ProductID,PaymentMethod , IFNULL(Amount,0) AS CashAmount FROM payments WHERE PaymentMethod = 'Check' GROUP BY ProductID , PaymentMethod) AS pr
ON pr.`PaymentMethod` = p.`PaymentMethod` AND pr.ProductID = p.`ProductID`
LEFT JOIN (SELECT ProductID, PaymentMethod , IFNULL(Amount,0) AS CashAmount FROM payments WHERE PaymentMethod = 'Credit Card' GROUP BY ProductID , PaymentMethod) AS px
ON px.`PaymentMethod` = p.`PaymentMethod` AND px.ProductID = p.`ProductID`
GROUP BY p.`ProductID` ;
Output
ProductID | Cash | Check | Credit Card | Amount
-----------------------------------------------
3 | 20 | 15 | 25 | 60
4 | 5 | 6 | 7 | 18
To break out from a ruby block simply use return
keyword
return if value.nil?
If you're working with a makefile and you ended up here like me, then this is probably what you're looking or:
If you're using a makefile, then you need to change cc
as shown below
my_executable : main.o
cc -o my_executable main.o
to
CC = g++
my_executable : main.o
$(CC) -o my_executable main.o
To position block elements to the center (works in IE9 and above), needs a wrapper div
:
.vcontainer {
position: relative;
top: 50%;
transform: translateY(-50%);
-webkit-transform: translateY(-50%);
}
If that is the entire line, it very well might be because you are missing a ;
at the end of the line.
Some ideas in the following answer:
Steps in creating a web service using Axis2 - The client code
Gives an example of a Groovy client invoking the ADB classes generated from the WSDL.
There are lots of web service frameworks out there...
There is actually a way to do this with html only. Just sets:
<img src="#" width height="50%">
...We don't have a newer version of MySQL yet, so I was able to do this (works only on UNIX):
host=maindb
echo "show full processlist\G" | mysql -h$host | grep -B 6 -A 1 Locked
The above will query for all locked sessions, and return the information and SQL that is involved.
...So- assuming you wanted to query for sessions that were sleeping:
host=maindb
echo "show full processlist\G" | mysql -h$host | grep -B 6 -A 1 Sleep
Or, assuming you needed to provide additional connection parameters for MySQL:
host=maindb
user=me
password=mycoolpassword
echo "show full processlist\G" | mysql -h$host -u$user -p$password | grep -B 6 -A 1 Locked
With a couple of tweaks, I'm sure a shell script could be easily created to query the processlist the way you want it.
For parseInt to work, your string should have only numerical data. Something like this:
str1 = "123.00";
str2 = "50.00";
total = parseInt(str1)+parseInt(str2);
alert(total);
Can you split the string before you start processing them for a total?
Try below, it will generate an app-debug.apk on your root/android/app/build/outputs/apk/debug folder
react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res
then go to android folder and run
./gradlew assembleDebug
You could use a watch instead, because that has the old and new value, but then you're adding to the digest cycle.
I'd just keep a second variable in the controller and set that.
Always use keydown.enter instead of keyup.enter to avoid lagging.
<textarea [(ngModel)]="textValue" (keydown.enter)="sendMessage();false" ></textarea>
and function inside component.ts
textValue : string = '';
sendMessage() {
console.log(this.textValue);
this.textValue = '';
}
Using John W answer I created an implementation that correctly begin the timeout when the task starts its execution. I even write a unit test for it :)
However, it does not suit my needs since some IO operations do not interrupt when Future.cancel()
is called (ie when Thread.interrupt()
is called).
Some examples of IO operation that may not be interrupted when Thread.interrupt()
is called are Socket.connect
and Socket.read
(and I suspect most of IO operation implemented in java.io
). All IO operations in java.nio
should be interruptible when Thread.interrupt()
is called. For example, that is the case for SocketChannel.open
and SocketChannel.read
.
Anyway if anyone is interested, I created a gist for a thread pool executor that allows tasks to timeout (if they are using interruptible operations...): https://gist.github.com/amanteaux/64c54a913c1ae34ad7b86db109cbc0bf
Added this as a comment to accepted answer, but felt it deserved a longer explanation. Starting around April 2015 this will probably be raised a few times.
As of V2 of the graph api the accepted answer no longer works using a username. So now you need the userid first, and you can no longer use a username to get this. To further complicate matters, for privacy reasons, Facebook is now changing userid's per app (see https://developers.facebook.com/docs/graph-api/reference/v2.2/user/ and https://developers.facebook.com/docs/apps/upgrading/#upgrading_v2_0_user_ids ), so you will have to have some kind of proper authentication to retrieve a userid you can use. Technically the profile pic is still public and available at /userid/picture (see docs at https://developers.facebook.com/docs/graph-api/reference/v2.0/user/picture and this example user: http://graph.facebook.com/v2.2/4/picture?redirect=0) however figuring out a user's standard userid seems impossible based just on their profile - your app would need to get them to approve interaction with the app which for my use case (just showing a profile pic next to their FB profile link) is overkill.
If someone has figured out a way to get the profile pic based on username, or alternatively, how to get a userid (even an alternating one) to use to retrieve a profile pic, please share! In the meantime, the old graph url still works until April 2015.
Extremely simple function to get human file size.
Original source: http://php.net/manual/de/function.filesize.php#106569
Copy/paste code:
<?php
function human_filesize($bytes, $decimals = 2) {
$sz = 'BKMGTP';
$factor = floor((strlen($bytes) - 1) / 3);
return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$sz[$factor];
}
?>
In simple words Autowiring, wiring links automatically, now comes the question who does this and which kind of wiring. Answer is: Container does this and Secondary type of wiring is supported, primitives need to be done manually.
Question: How container know what type of wiring ?
Answer: We define it as byType,byName,constructor.
Question: Is there are way we do not define type of autowiring ?
Answer: Yes, it's there by doing one annotation, @Autowired.
Question: But how system know, I need to pick this type of secondary data ?
Answer: You will provide that data in you spring.xml file or by using sterotype annotations to your class so that container can themselves create the objects for you.
I would add another column on the data sheet with equation =month(A2), then run the countif on that column... If you still wanted to use text month('APRIL'), you would need a lookup table to reference the name to the month number. Otherwise, just use 4 instead of April on your metric sheet.
The meaning of the word can differ a lot with context. In general, it's resources (most often memory and CPU time) that are used, which do not contribute directly to the intended result, but are required by the technology or method that is being used. Examples:
Wouldn't it be better to not use any dynamic types for this, and let your class implement an interface. Then, you can check at runtime wether an object implements that interface, and thus, has the expected method (or property).
public interface IMyInterface
{
void Somemethod();
}
IMyInterface x = anyObject as IMyInterface;
if( x != null )
{
x.Somemethod();
}
I think this is the only correct way.
The thing you're referring to is duck-typing, which is useful in scenarios where you already know that the object has the method, but the compiler cannot check for that. This is useful in COM interop scenarios for instance. (check this article)
If you want to combine duck-typing with reflection for instance, then I think you're missing the goal of duck-typing.
Yes, you can run PHP in an HTML page.
I have successfully executed PHP code in my HTML files for many years. (For the curious, this is because I have over 8,000 static HTML files created by me and others over the last 20 years and I didn't want to lose search engine ranking by changing them and, more importantly, I have too many other things to work on).
I am not an expert -- below is what I've tried and what works for me. Please don't ask me to explain it.
Everything below involves adding a line or two to your .htaccess file.
Here is what one host ( http://simolyhosting.net ) support did for me in 2008 -- but it no longer works for me now.
AddHandler application/x-httpd-php5 .html .htm
AddType application/x-httpd-php5 .htm .html
That solution appears to be deprecated now, though it might work for you.
Here's what's working for me now:
AddType application/x-httpd-lsphp .htm .html
(This page has PHP code that executes properly with the above solution -- http://mykindred.com/bumstead/steeplehistory.htm )
Below are other solutions I found -- they are NOT MINE:
https://forums.cpanel.net/threads/cant-execute-php-in-html-since-ea4-upgrade.569531
I'm seeing this across many servers I've recently upgraded to EA4. Using cPanel Apache handlers or adding this directly in to .htaccess (same as cPanel does through gui add handlers):
AddHandler application/x-httpd-php5 .html
Sep 9, 2016
AddHandler application/x-httpd-ea-php56 .html
Open a text editor such as wordpad, notepad, nano, etc. and add the following line:
AddHandler x-mapp-php5 .html .htm
If you want to use PHP 5.4 instead of PHP 5.2 then use the following line instead:
AddHandler x-mapp-php6 .html .htm
https://www.godaddy.com/community/Developer-Cloud-Portal/Running-php-in-html-files/td-p/2776
To run HTML using FastCGI/PHP, try adding this code to the .htaccess file for the directory the script is in:
Options +ExecCGI
AddHandler fcgid-script .html
FCGIWrapper /usr/local/cpanel/cgi-sys/php5 .html
You can add additional lines for other file extensions if needed.
if (isset($_POST['submit'])) {
for($i = 0; $i<= 3; $i++){
if(isset($_POST['books'][$i]))
$book .= ' '.$_POST['books'][$i];
}
You can do the following:
public class Numbers {
private int number1 = 50;
private int number2 = 100;
private List<Integer> list;
public Numbers() {
list = new ArrayList<Integer>();
list.add(number1);
list.add(number2);
}
int getNumber(int pos)
{
return list.get(pos);
}
}
public class Test {
private Numbers numbers;
public Test(){
numbers = new Numbers();
int number1 = numbers.getNumber(0);
int number2 = numbers.getNumber(1);
}
}
best solution: from jQuery v1.6 you can use prop() to add a property
$('#someid').prop('disabled', true);
to remove it, use removeProp()
$('#someid').removeProp('disabled');
Also note that the .removeProp() method should not be used to set these properties to false. Once a native property is removed, it cannot be added again. See .removeProp() for more information.
CSS to detect screen orientation:
@media screen and (orientation:portrait) { … }
@media screen and (orientation:landscape) { … }
The CSS definition of a media query is at http://www.w3.org/TR/css3-mediaqueries/#orientation
While some of these answers are pretty good, I feel like none actually answered the OP's original constraint: selecting particular files from particular branches. This solution does that, but it may be tedious if there are many files.
Let’s say you have the master
, exp1
, and exp2
branches. You want to merge one file from each of the experimental branches into master. I would do something like this:
git checkout master
git checkout exp1 path/to/file_a
git checkout exp2 path/to/file_b
# Save these files as a stash
git stash
# Merge stash with master
git merge stash
This will give you in-file diffs for each of the files you want. Nothing more. Nothing less. It's useful you have radically different file changes between versions --in my case, changing an application from Ruby on Rails 2 to Ruby on Rails 3.
This will merge files, but it does a smart merge. I wasn't able to figure out how to use this method to get in-file diff information (maybe it still will for extreme differences. Annoying small things like whitespace get merged back in unless you use the -s recursive -X ignore-all-space
option)
Resolve is also more straightforward
from django.urls import resolve
resolve('edit_project', project_id=4)
This is how I do it:
using System.IO;
using System.Security.Cryptography;
public string checkMD5(string filename)
{
using (var md5 = MD5.Create())
{
using (var stream = File.OpenRead(filename))
{
return Encoding.Default.GetString(md5.ComputeHash(stream));
}
}
}
from operator import is_not
from functools import partial
filter_null = partial(filter, partial(is_not, None))
# A test case
L = [1, None, 2, None, 3]
L = list(filter_null(L))
I am of the firm belief that in an Entity Relation Diagram, the entity should be reflected with a singular name, similar to a class name being singular. Once instantiated, the name reflects its instance. So with databases, the entity when made into a table (a collection of entities or records) is plural. Entity, User is made into table Users. I would agree with others who suggested maybe the name User could be improved to Employee or something more applicable to your scenario.
This then makes more sense in a SQL statement because you are selecting from a group of records and if the table name is singular, it doesn't read well.
It is not necessary to use withRouter. This works for me:
In your parent page,
<BrowserRouter>
<Switch>
<Route path="/routeA" render={(props)=> (
<ComponentA {...props} propDummy={50} />
)} />
<Route path="/routeB" render={(props)=> (
<ComponentB {...props} propWhatever={100} />
)} />
</Switch>
</BrowserRouter>
Then in ComponentA or ComponentB you can access
this.props.history
object, including the this.props.history.push method.
Personally I don't find the standard diagramming technique very helpful - the arrows always seem to point the wrong way for me. (They generally point towards the "parent" of each commit, which ends up being backwards in time, which is weird).
To explain it in words:
For reasons I don't understand, GUI tools for Git have never made much of an effort to present merge histories more cleanly, abstracting out the individual merges. So if you want a "clean history", you need to use rebase.
I seem to recall having read blog posts from programmers who only use rebase and others that never use rebase.
I'll try explaining this with a just-words example. Let's say other people on your project are working on the user interface, and you're writing documentation. Without rebase, your history might look something like:
Write tutorial
Merge remote-tracking branch 'origin/master' into fixdocs
Bigger buttons
Drop down list
Extend README
Merge remote-tracking branch 'origin/master' into fixdocs
Make window larger
Fix a mistake in howto.md
That is, merges and UI commits in the middle of your documentation commits.
If you rebased your code onto master instead of merging it, it would look like this:
Write tutorial
Extend README
Fix a mistake in howto.md
Bigger buttons
Drop down list
Make window larger
All of your commits are at the top (newest), followed by the rest of the master
branch.
(Disclaimer: I'm the author of the "10 things I hate about Git" post referred to in another answer)
What worked for me: I finally noticed the Build Executor Status window on the left on the main Jenkins dashboard. I run a dev/test instance on my local system with 2 executors. Both were currently occupied with builds that were not running. Upon cancelling these to jobs, my third (pending) job was able to run.
The outline
property is what you need. It's shorthand for setting each of the following properties in a single declaration:
outline-style
outline-width
outline-color
You could use outline: none;
, which is suggested in the accepted answer. You could also be more specific if you wanted:
button {
outline-style: none;
}
From the man page for time:
/usr/bin/time
You can provide a format string and one of the format options is elapsed time - e.g. %E
/usr/bin/time -f'%E' $CMD
Example:
$ /usr/bin/time -f'%E' ls /tmp/mako/
res.py res.pyc
0:00.01
You can use html5 video player which has full screen playback option.
This is a very good html5 player to have a look.
http://sublimevideo.net/
Try this
DECLARE @String VARCHAR(100)
SET @String = 'TEST STRING'
SELECT LEFT(@String, LEN(@String) - 1) AS MyTrimmedColumn
Sure. On my (pretty vanilla) Cygwin setup, bash
is in c:\cygwin\bin
so I can run a bash
script (say testit.sh
) from a Windows batch file using a command like:
C:\cygwin\bin\bash testit.sh
... which can be included in a .bat
file as easily as it can be typed at the command line, and with the same effect.
Basically if the response header is text/html you need to parse, and if the response header is application/json it is already parsed for you.
Parsed data from jquery success handler for text/html response:
var parsed = JSON.parse(data);
Parsed data from jquery success handler for application/json response:
var parsed = data;
Below is a good solution in Java though!
NumberFormat fmt = NumberFormat.getCurrencyInstance();
System.out.println(fmt.format(n));
or for a more robust way you may want to get the locale of a particular place, then use as below:
int n=9999999;
Locale locale = new Locale("en", "US");
NumberFormat fmt = NumberFormat.getCurrencyInstance(locale);
System.out.println(fmt.format(n));
US Locale OUTPUT: $9,999,999.00
German Locale output
Locale locale = new Locale("de", "DE");
OUTPUT: 9.999.999,00 €
Indian Locale output
Locale locale = new Locale("de", "DE");
OUTPUT: Rs.9,999,999.00
Estonian Locale output
Locale locale = new Locale("et", "EE");
OUTPUT: 9 999 999 €
As you can see in different outputs you don't have to worry about the separator being a comma or dot or even space you can get the number formatted according to the i18n standards
Have you tried loading the socket.io script not from a relative URL?
You're using:
<script src="socket.io/socket.io.js"></script>
And:
socket.connect('http://127.0.0.1:8080');
You should try:
<script src="http://localhost:8080/socket.io/socket.io.js"></script>
And:
socket.connect('http://localhost:8080');
Switch localhost:8080
with whatever fits your current setup.
Also, depending on your setup, you may have some issues communicating to the server when loading the client page from a different domain (same-origin policy). This can be overcome in different ways (outside of the scope of this answer, google/SO it).
git show <revhash>
Documentation here. Or if that doesn't work, try Google Code's GIT Documentation
We can also use ngClass to assign multiple CSS classes based on multiple conditions as below:
<div
[ngClass]="{
'class-name': trueCondition,
'other-class': !trueCondition
}"
></div>
I got this error when invoking a function from a Laravel Controller to a PHP file.
After a couple of hours, I found the problem: I was using $this from within a static function.
The actual values are in radians but to interpret them in degrees it will be:
atan
= gives angle value between -90 and 90atan2
= gives angle value between -180 and 180For my work which involves computation of various angles such as heading and bearing in navigation, atan2
in most cases does the job.
APIs are messy because they keep changing. This pure javascript way worked for me:
<div id="divScope" class="boom-lightbox" style="display: none;">
<iframe id="ytplayer" width="720" height="405" src="https://www.youtube.com/embed/M7lc1UVf-VE" frameborder="0" allowfullscreen> </iframe>
</div>
//if I want i can set scope to a specific region
var myScope = document.getElementById('divScope');
//otherwise set scope as the entire document
//var myScope = document;
//if there is an iframe inside maybe embedded multimedia video/audio, we should reload so it stops playing
var iframes = myScope.getElementsByTagName("iframe");
if (iframes != null) {
for (var i = 0; i < iframes.length; i++) {
iframes[i].src = iframes[i].src; //causes a reload so it stops playing, music, video, etc.
}
}
Binding="{Binding YourColumn ,StringFormat='yyyy-MM-dd'}"
First, factor consists of indices and levels. This fact is very very important when you are struggling with factor.
For example,
> z <- factor(letters[c(3, 2, 3, 4)])
# human-friendly display, but internal structure is invisible
> z
[1] c b c d
Levels: b c d
# internal structure of factor
> unclass(z)
[1] 2 1 2 3
attr(,"levels")
[1] "b" "c" "d"
here, z
has 4 elements.
The index is 2, 1, 2, 3
in that order.
The level is associated with each index: 1 -> b, 2 -> c, 3 -> d.
Then, as.numeric
converts simply the index part of factor into numeric.
as.character
handles the index and levels, and generates character vector expressed by its level.
?as.numeric
says that Factors are handled by the default method.
While jkp's solution works, the newer way of doing things (and the way the documentation recommends) is to use the subprocess
module. For simple commands its equivalent, but it offers more options if you want to do something complicated.
Example for your case:
import subprocess
subprocess.Popen(["rm","-r","some.file"])
This will run rm -r some.file
in the background. Note that calling .communicate()
on the object returned from Popen
will block until it completes, so don't do that if you want it to run in the background:
import subprocess
ls_output=subprocess.Popen(["sleep", "30"])
ls_output.communicate() # Will block for 30 seconds
See the documentation here.
Also, a point of clarification: "Background" as you use it here is purely a shell concept; technically, what you mean is that you want to spawn a process without blocking while you wait for it to complete. However, I've used "background" here to refer to shell-background-like behavior.
Just for completeness, you don't actually have to add it to your HTML (which is unknown http-equiv in HTML5)
Do this and never look back (first example for apache, second for nginx)
Header set X-UA-Compatible "IE=Edge,chrome=1"
add_header X-UA-Compatible "IE=Edge,chrome=1";
Thanks you all! Now it's work. DATAJPA-231
It will be nice if was possible to create count…By… methods just like find…By ones. Example:
public interface UserRepository extends JpaRepository<User, Long> {
public Long /*or BigInteger */ countByActiveTrue();
}
You can stream download too which will consume significantly less resource. example:
$readableStream = fopen('test.zip', 'rb');
$writableStream = fopen('php://output', 'wb');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="test.zip"');
stream_copy_to_stream($readableStream, $writableStream);
ob_flush();
flush();
In the above example, I am downloading a test.zip (which was actually the android studio zip on my local machine).
php://output is a write-only stream (generally used by echo or print).
after that, you just need to set the required headers and call stream_copy_to_stream(source, destination).
stream_copy_to_stream() method acts as a pipe which takes the input from the source stream (read stream) and pipes it to the destination stream (write stream) and it also avoid the issue of allowed memory exhausted so you can actually download files that are bigger than your PHP memory_limit
.
<http pattern="/resources/**" security="none"/>
Or with Java configuration:
web.ignoring().antMatchers("/resources/**");
Instead of the old:
<intercept-url pattern="/resources/**" filters="none"/>
for exp . disable security for a login page :
<intercept-url pattern="/login*" filters="none" />
The simplest solution without changing the default style is:
<Style TargetType="Button" x:Key="RoundButton">
<Style.Resources>
<Style TargetType="Border">
<Setter Property="CornerRadius" Value="5" />
</Style>
</Style.Resources>
</Style>
Then just define your button like this:
<Button Style="{DynamicResource RoundButton}" />
What I believe user2087510 meant was:
name = 'something'
name = name.replace("'", "\\'")
I have also used this with success.
%Lf
(note the capital L
) is the format specifier for long doubles.
For plain doubles
, either %e
, %E
, %f
, %g
or %G
will do.
You can write a simple gradle script to print your GRADLE_HOME
directory.
task getHomeDir {
doLast {
println gradle.gradleHomeDir
}
}
and name it build.gradle
.
Then run it with:
gradle getHomeDir
If you installed with homebrew, use brew info gradle
to find the base path (i.e. /usr/local/Cellar/gradle/1.10/
), and just append libexec
.
The same task in Kotlin in case you use build.gradle.kts
:
tasks.register("getHomeDir") {
println("Gradle home dir: ${gradle.gradleHomeDir}")
}
Development Phase:
Step 1: Create Certificate .pem from Certificate .p12
openssl pkcs12 -clcerts -nokeys -out apns-dev-cert.pem -in apns-dev-cert.p12
Step 2: Create Key .pem from Key .p12
openssl pkcs12 -nocerts -out apns-dev-key.pem -in apns-dev-key.p12
Step 3 (Optional): If you want to remove pass phrase asked in second step
openssl rsa -in apns-dev-key.pem -out apns-dev-key-noenc.pem
Step 4: Now we have to merge the Key .pem and Certificate .pem to get Development .pem needed for Push Notifications in Development Phase of App.
If 3rd step was performed, run:
cat apns-dev-cert.pem apns-dev-key-noenc.pem > apns-dev.pem
If 3rd step was not performed, run:
cat apns-dev-cert.pem apns-dev-key.pem > apns-dev.pem
Step 5: Check certificate validity and connectivity to APNS
If 3rd step was performed, run:
openssl s_client -connect gateway.sandbox.push.apple.com:2195 -cert apns-dev-cert.pem -key apns-dev-key-noenc.pem
If 3rd step was not performed, run:
openssl s_client -connect gateway.sandbox.push.apple.com:2195 -cert apns-dev-cert.pem -key apns-dev-key.pem
Production Phase:
Step 1: Create Certificate .pem from Certificate .p12
openssl pkcs12 -clcerts -nokeys -out apns-pro-cert.pem -in apns-pro-cert.p12
Step 2: Create Key .pem from Key .p12
openssl pkcs12 -nocerts -out apns-pro-key.pem -in apns-pro-key.p12
Step 3 (Optional): If you want to remove pass phrase asked in second step
openssl rsa -in apns-pro-key.pem -out apns-pro-key-noenc.pem
Step 4: Now we have to merge the Key .pem and Certificate .pem to get Production .pem needed for Push Notifications in Production Phase of App.
If 3rd step was performed, run:
cat apns-pro-cert.pem apns-pro-key-noenc.pem > apns-pro.pem
If 3rd step was not performed, run:
cat apns-pro-cert.pem apns-pro-key.pem > apns-pro.pem
Step 5: Check certificate validity and connectivity to APNS.
If 3rd step was performed, run:
openssl s_client -connect gateway.push.apple.com:2195 -cert apns-pro-cert.pem -key apns-pro-key-noenc.pem
If 3rd step was not performed, run:
openssl s_client -connect gateway.push.apple.com:2195 -cert apns-pro-cert.pem -key apns-pro-key.pem
All the methods above do not handle deep cloning of objects where it is nested to n levels. I did not check its performance over others but it is short and simple.
The first example below shows object cloning using Object.assign
which clones just till first level.
var person = {_x000D_
name:'saksham',_x000D_
age:22,_x000D_
skills: {_x000D_
lang:'javascript',_x000D_
experience:5_x000D_
}_x000D_
}_x000D_
_x000D_
newPerson = Object.assign({},person);_x000D_
newPerson.skills.lang = 'angular';_x000D_
console.log(newPerson.skills.lang); //logs Angular
_x000D_
Using the below approach deep clones object
var person = {_x000D_
name:'saksham',_x000D_
age:22,_x000D_
skills: {_x000D_
lang:'javascript',_x000D_
experience:5_x000D_
}_x000D_
}_x000D_
_x000D_
anotherNewPerson = JSON.parse(JSON.stringify(person));_x000D_
anotherNewPerson.skills.lang = 'angular';_x000D_
console.log(person.skills.lang); //logs javascript
_x000D_
Not sure about how other people solve this problem or whether Bootstrap has any configuration for this.
I found this thread that provides a solution:
https://github.com/twbs/bootstrap/issues/1411
One of the post suggests the use of
<ul class="dropdown-menu" style="right: 0; left: auto;">
I tested and it works.
Hope to know whether Bootstrap provides config for doing this, not via the above css.
Cheers.
I'll add my two cents just as a way to discover files with a specific ownership inside a directory.
The issue was caused by running some git command as root. The received message was:
$ git commit -a -m "fix xxx"
error: insufficient permission for adding an object to repository database .git/objects
error: setup.sh: failed to insert into database
I first looked at git config -l
, then I resolved with:
find .git/ -exec stat --format="%G %n" {} + |grep root
chown -R $(id -un):$(id -gn) .git/objects/
git commit -a -m "fixed git objects ownership"
If you want to do something like,User enter url "www.xxxxxx.com/views/root/" & default page is displayed then I guess you have to set the default/home/welcome page attribute in IIS. But if user just enters "www.xxxxxx.com" and you still want to forward to your url, then you have write a line of code in the default page to forward to your desired url. This default page should be in root directory of your application, so www.xxxxx.com will load www.xxxx.com/index.html which will redirect the user to your desired url
Case where multiple certificates are needed was solved as follows: Concatenate the multiple root pem files, myCert-A-Root.pem and myCert-B-Root.pem, to a file. Then set the requests REQUESTS_CA_BUNDLE var to that file in my ./.bash_profile.
$ cp myCert-A-Root.pem ca_roots.pem
$ cat myCert-B-Root.pem >> ca_roots.pem
$ echo "export REQUESTS_CA_BUNDLE=~/PATH_TO/CA_CHAIN/ca_roots.pem" >> ~/.bash_profile ; source ~/.bash_profile
I could not get IE8+ to work by adding a jQuery event handler to the file input type. I had to go old-school and add the the onchange=""
attribute to the input tag:
<input type='file' onchange='getFilename(this)'/>
function getFileName(elm) {
var fn = $(elm).val();
....
}
EDIT:
function getFileName(elm) {
var fn = $(elm).val();
var filename = fn.match(/[^\\/]*$/)[0]; // remove C:\fakename
alert(filename);
}
Below is the script which is integrated into ansible and generating dashboard in CSV format.
sh collection.sh
#!/bin/bash
HOSTNAME=`hostname -s`
for i in `cat /etc/passwd| grep -vE "nologin|shutd|hal|sync|root|false"|awk -F':' '{print$1}' | sed 's/[[:space:]]/,/g'`; do groups $i; done|sed s/\:/\,/g|tr -d ' '|sed -e "s/^/$HOSTNAME,/"> /tmp/"$HOSTNAME"_inventory.txt
sudo cat /etc/sudoers| grep -v "^#"|awk '{print $1}'|grep -v Defaults|sed '/^$/d;s/[[:blank:]]//g'>/tmp/"$HOSTNAME"_sudo.txt
paste -d , /tmp/"$HOSTNAME"_inventory.txt /tmp/"$HOSTNAME"_sudo.txt|sed 's/,[[:blank:]]*$//g' >/tmp/"$HOSTNAME"_inventory_users.txt
My output stored in below text files.
cat /tmp/ANSIBLENODE_sudo.txt
cat /tmp/ANSIBLENODE_inventory.txt
cat /tmp/ANSIBLENODE_inventory_users.txt
eric, your code did not seem to work for me when the user enters text then deletes all the text. i created another version if anyone experienced the same problem. here ya go folks:
$('input[type="submit"]').attr('disabled','disabled');
$('input[type="text"]').keyup(function(){
if($('input[type="text"]').val() == ""){
$('input[type="submit"]').attr('disabled','disabled');
}
else{
$('input[type="submit"]').removeAttr('disabled');
}
})
The permament pool contains everything that is not your application data, but rather things required for the VM: typically it contains interned strings, the byte code of defined classes, but also other "not yours" pieces of data.
try this code ['12','34','35','231']*","
will give you result "12,34,35,231"
I hope this is the result you, let me know
If you simply want some output, you want to use $(info)
by itself. You can do that anywhere in a Makefile, and it will show when that line is evaluated:
$(info VAR="$(VAR)")
Will output VAR="<value of VAR>"
whenever make processes that line. This behavior is very position dependent, so you must make sure that the $(info)
expansion happens AFTER everything that could modify $(VAR)
has already happened!
A more generic option is to create a special rule for printing the value of a variable. Generally speaking, rules are executed after variables are assigned, so this will show you the value that is actually being used. (Though, it is possible for a rule to change a variable.) Good formatting will help clarify what a variable is set to, and the $(flavor)
function will tell you what kind of a variable something is. So in this rule:
print-% : ; $(info $* is a $(flavor $*) variable set to [$($*)]) @true
$*
expands to the stem that the %
pattern matched in the rule.$($*)
expands to the value of the variable whose name is given by by $*
.[
and ]
clearly delineate the variable expansion.
You could also use "
and "
or similar.$(flavor $*)
tells you what kind of variable it is. NOTE: $(flavor)
takes a variable name, and not its expansion.
So if you say make print-LDFLAGS
, you get $(flavor LDFLAGS)
,
which is what you want.$(info text)
provides output.
Make prints text
on its stdout as a side-effect of the expansion.
The expansion of $(info)
though is empty.
You can think of it like @echo
,
but importantly it doesn't use the shell,
so you don't have to worry about shell quoting rules.@true
is there just to provide a command for the rule.
Without that,
make will also output print-blah is up to date
. I feel @true
makes it more clear that it's meant to be a no-op.Running it, you get
$ make print-LDFLAGS
LDFLAGS is a recursive variable set to [-L/Users/...]
While using backticks or popen is often what you really want, it doesn't actually answer the question asked. There may be valid reasons for capturing system
output (maybe for automated testing). A little Googling turned up an answer I thought I would post here for the benefit of others.
Since I needed this for testing my example uses a block setup to capture the standard output since the actual system
call is buried in the code being tested:
require 'tempfile'
def capture_stdout
stdout = $stdout.dup
Tempfile.open 'stdout-redirect' do |temp|
$stdout.reopen temp.path, 'w+'
yield if block_given?
$stdout.reopen stdout
temp.read
end
end
This method captures any output in the given block using a tempfile to store the actual data. Example usage:
captured_content = capture_stdout do
system 'echo foo'
end
puts captured_content
You can replace the system
call with anything that internally calls system
. You could also use a similar method to capture stderr
if you wanted.
insert byte to specific place.
insertToArray(arr,index,item) {
return Buffer.concat([arr.slice(0,index),Buffer.from(item,"utf-8"),arr.slice(index)]);
}
Customize the filter, and determine what kind of abnormality, there should be a better method than this
public class ExceptionFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
String msg = "";
try {
filterChain.doFilter(request, response);
} catch (Exception e) {
if (e instanceof JwtException) {
msg = e.getMessage();
}
response.setCharacterEncoding("UTF-8");
response.setContentType(MediaType.APPLICATION_JSON.getType());
response.getWriter().write(JSON.toJSONString(Resp.error(msg)));
return;
}
}
}
I've found a working code:
JSONParser parser = new JSONParser();
Object obj = parser.parse(content);
JSONArray array = new JSONArray();
array.add(obj);
Or you can simply start the activity as shown below;
startActivity( new Intent(currentactivity.this, Tostartactivity.class));
there is no actual overloading in JS, anyway we still can simulate method overloading in several ways:
method #1: use object
function test(x,options){
if("a" in options)doSomething();
else if("b" in options)doSomethingElse();
}
test("ok",{a:1});
test("ok",{b:"string"});
method #2: use rest (spread) parameters
function test(x,...p){
if(p[2])console.log("3 params passed"); //or if(typeof p[2]=="string")
else if (p[1])console.log("2 params passed");
else console.log("1 param passed");
}
method #3: use undefined
function test(x, y, z){
if(typeof(z)=="undefined")doSomething();
}
method #4: type checking
function test(x){
if(typeof(x)=="string")console.log("a string passed")
else ...
}
def get_true_text(tag):
children = tag.find_elements_by_xpath('*')
original_text = tag.text
for child in children:
original_text = original_text.replace(child.text, '', 1)
return original_text
Similar to @??? I had the wrong application type configured for a dll. I guess that the project type changed due to some bad copy pasting, as @Daniel Struhl suggested.
How to verify:
Right click on the project -> properties
-> Configuration Properties
-> General
-> Project Defaults
-> Configuration Type
.
Check if this field contains the correct type, e.g. "Dynamic Library (.dll)" in case the project is a dll.
Just use:
<TextBlock Text="{Binding Date, StringFormat=\{0:d\}}" />
Just for the reference, if you work in scripts (batch processing), not in stored procedure, flushing output is triggered by the GO command, e.g.
print 'test'
print 'test'
go
In general, my conclusion is following: output of mssql script execution, executing in SMS GUI or with sqlcmd.exe, is flushed to file, stdoutput, gui window on first GO statement or until the end of the script.
Flushing inside of stored procedure functions differently, since you can not place GO inside.
Reference: tsql Go statement