As suggested in other answers it's probably easiest to "POST" the form data to the controller. If you need to pass an entire Model/Form you can easily do this with serialize()
e.g.
$('#myform').on('submit', function(e){
e.preventDefault();
var formData = $(this).serialize();
$.post('/student/update', formData, function(response){
//Do something with response
});
});
So your controller could have a view model as the param e.g.
[HttpPost]
public JsonResult Update(StudentViewModel studentViewModel)
{}
Alternatively if you just want to post some specific values you can do:
$('#myform').on('submit', function(e){
e.preventDefault();
var studentId = $(this).find('#Student_StudentId');
var isActive = $(this).find('#Student_IsActive');
$.post('/my/url', {studentId : studentId, isActive : isActive}, function(response){
//Do something with response
});
});
With a controller like:
[HttpPost]
public JsonResult Update(int studentId, bool isActive)
{}
This error is very non-descriptive but the key here is that 'ID' is in uppercase. This indicates that the route has not been correctly set up. To let the application handle URLs with an id, you need to make sure that there's at least one route configured for it. You do this in the RouteConfig.cs located in the App_Start folder. The most common is to add the id as an optional parameter to the default route.
public static void RegisterRoutes(RouteCollection routes)
{
//adding the {id} and setting is as optional so that you do not need to use it for every action
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Now you should be able to redirect to your controller the way you have set it up.
[HttpPost]
public ActionResult RedirectToImages(int id)
{
return RedirectToAction("Index","ProductImageManager", new { id });
//if the action is in the same controller, you can omit the controller:
//RedirectToAction("Index", new { id });
}
In one or two occassions way back I ran into some issues by normal redirect and had to resort to doing it by passing a RouteValueDictionary. More information on RedirectToAction with parameter
return RedirectToAction("Index", new RouteValueDictionary(
new { controller = "ProductImageManager", action = "Index", id = id } )
);
If you get a very similar error but in lowercase 'id', this is usually because the route expects an id parameter that has not been provided (calling a route without the id /ProductImageManager/Index
). See this so question for more information.
While you are declaring onclick in XML then you must declair method and pass View v as parameter and make the method public...
Ex:
//in xml
android:onClick="onButtonClicked"
// in java file
public void onButtonClicked(View v)
{
//your code here
}
Passing data from Fragment to another Fragment
From first Fragment
// Set data to pass
MyFragment fragment = new MyFragment(); //Your Fragment
Bundle bundle = new Bundle();
bundle.putInt("year", 2017) // Key, value
fragment.setArguments(bundle);
// Pass data to other Fragment
getFragmentManager()
.beginTransaction()
.replace(R.id.content, fragment)
.commit();
On Second Fragment
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = this.getArguments();
if (bundle != null) {
Int receivedYear = bundle.getInt("year", ""); // Key, default value
}
}
Change the code where you load the partial view to:
@Html.Partial("_CreateNote", new QuickNotes.Models.Note())
This is because the partial view is expecting a Note but is getting passed the model of the parent view which is the IEnumerable
You can use:
window.location.href = '/Branch/Details/' + id;
But your Ajax code is incomplete without success or error functions.
If you want to load the partial view directly inside the main view you could use the Html.Action
helper:
@Html.Action("Load", "Home")
or if you don't want to go through the Load action use the HtmlPartialAsync helper:
@await Html.PartialAsync("_LoadView")
If you want to use Ajax.ActionLink
, replace your Html.ActionLink
with:
@Ajax.ActionLink(
"load partial view",
"Load",
"Home",
new AjaxOptions { UpdateTargetId = "result" }
)
and of course you need to include a holder in your page where the partial will be displayed:
<div id="result"></div>
Also don't forget to include:
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
in your main view in order to enable Ajax.*
helpers. And make sure that unobtrusive javascript is enabled in your web.config (it should be by default):
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
In Controller i have specified the below code with ActionResult which is a base class that can have 11 subtypes in MVC like: ViewResult, PartialViewResult, EmptyResult, RedirectResult, RedirectToRouteResult, JsonResult, JavaScriptResult, ContentResult, FileContentResult, FileStreamResult, FilePathResult.
public ActionResult Index()
{
if (HttpContext.Session["LoggedInUser"] == null)
{
return RedirectToAction("Login", "Home");
}
else
{
return View(); // returns ViewResult
}
}
//More Examples
[HttpPost]
public ActionResult Index(string Name)
{
ViewBag.Message = "Hello";
return Redirect("Account/Login"); //returns RedirectResult
}
[HttpPost]
public ActionResult Index(string Name)
{
return RedirectToRoute("RouteName"); // returns RedirectToRouteResult
}
Likewise we can return all these 11 subtypes by using ActionResult() without specifying every subtype method explicitly. ActionResult is the best thing if you are returning different types of views.
The easiest solution to workaround this is to create 'temporary' input with type submit and trigger click:
var submitInput = $("<input type='submit' />");
$("#aspnetForm").append(submitInput);
submitInput.trigger("click");
UPDATE: 30.07.2014
If you use Android Studio, make sure you have at least 144x144 resource and than use "FILE-NEW-IMAGE ASSET". Android Studio will make proper image files to all folders for you : )
As documentation says, adjust bitmaps as follows:
Almost every application should have alternative drawable resources for different screen densities, because almost every application has a launcher icon and that icon should look good on all screen densities. Likewise, if you include other bitmap drawables in your application (such as for menu icons or other graphics in your application), you should provide alternative versions or each one, for different densities.
Note: You only need to provide density-specific drawables for bitmap files (.png, .jpg, or .gif) and Nine-Path files (.9.png). If you use XML files to define shapes, colors, or other drawable resources, you should put one copy in the default drawable directory (drawable/).
To create alternative bitmap drawables for different densities, you should follow the 3:4:6:8 scaling ratio between the four generalized densities. For example, if you have a bitmap drawable that's 48x48 pixels for medium-density screen (the size for a launcher icon), all the different sizes should be:
36x36 for low-density (LDPI)
48x48 for medium-density (MDPI)
72x72 for high-density (HDPI)
96x96 for extra high-density (XHDPI)
144x144 for extra extra high-density (XXHDPI)
192x192 for extra extra extra high-density (XXXHDPI)
Proximity Sensor Dial
*#*#7378423#*#*
1) Service Tests - (If present)
2) Proximity Switch
3) Test on sensor (Next to logo(top) of mobile)
4) Yes if works, then u can keep on and proximity switch forever which gives beep all the time and consumes lot of battery
OR
4) No it doesn't work - Then simply clean the mobile screen or screen guard and clear the blocked screen from sensor. It works charm.
Technically, Its not any software solution, but hardware solution will work.
So you really want:
for each tweet
unless tweet is in db
insert tweet
If so, just write it down in your programming language. Hint: The loop over the array is to be done before the insert, which is done depending on the outcome.
What you want to test is that all array elements are not equal to the current one. But your for loop does not do that.
cp -r ./SourceFolder ./DestFolder
You are printing a formatted string. The {0} means to insert the first parameter following the format string; in this case the value associated with the key "rtf".
For String.Format, which is similar, if you had something like
// Format string {0} {1}
String.Format("This {0}. The value is {1}.", "is a test", 42 )
you'd create a string "This is a test. The value is 42".
You can also use expressions, and print values out multiple times:
// Format string {0} {1} {2}
String.Format("Fib: {0}, {0}, {1}, {2}", 1, 1+1, 1+2)
yielding "Fib: 1, 1, 2, 3"
See more at http://msdn.microsoft.com/en-us/library/txafckwd.aspx, which talks about composite formatting.
There is a data structure called deque
or double ended queue which is faster and efficient than a list. You can use your list and convert it to deque and do the required transformations in it. You can also convert the deque back to list.
import collections
mylist = [0, 1, 2, 3, 4]
#make a deque from your list
de = collections.deque(mylist)
#you can remove from a deque from either left side or right side
de.popleft()
print(de)
#you can covert the deque back to list
mylist = list(de)
print(mylist)
Deque also provides very useful functions like inserting elements to either side of the list or to any specific index. You can also rotate or reverse a deque. Give it a try!
I used Fittext on some of my projects and it looks like a good solution to a problem like this.
FitText makes font-sizes flexible. Use this plugin on your fluid or responsive layout to achieve scalable headlines that fill the width of a parent element.
Same Error was coming with my code in Activity but not in Fragment. Showing constructor error for different line like new Intent( From.this, To.class) and new ArrayList<> etc.
Fixed using closing Android Studio and moving the repository to other location and opening the the project once again. Fixed the problem.
Seems like Android Studio building problem.
Basic:
string[] myString = new string[]{"string1", "string2"};
or
string[] myString = new string[4];
myString[0] = "string1"; // etc.
Advanced: From a List
list<string> = new list<string>();
//... read this in from somewhere
string[] myString = list.ToArray();
From StringCollection
StringCollection sc = new StringCollection();
/// read in from file or something
string[] myString = sc.ToArray();
Arrays have numerical indexes. So,
a = new Array();
a['a1']='foo';
a['a2']='bar';
and
b = new Array(2);
b['b1']='foo';
b['b2']='bar';
are not adding elements to the array, but adding .a1
and .a2
properties to the a
object (arrays are objects too). As further evidence, if you did this:
a = new Array();
a['a1']='foo';
a['a2']='bar';
console.log(a.length); // outputs zero because there are no items in the array
Your third option:
c=['c1','c2','c3'];
is assigning the variable c
an array with three elements. Those three elements can be accessed as: c[0]
, c[1]
and c[2]
. In other words, c[0] === 'c1'
and c.length === 3
.
Javascript does not use its array functionality for what other languages call associative arrays where you can use any type of key in the array. You can implement most of the functionality of an associative array by just using an object in javascript where each item is just a property like this.
a = {};
a['a1']='foo';
a['a2']='bar';
It is generally a mistake to use an array for this purpose as it just confuses people reading your code and leads to false assumptions about how the code works.
You can use strcmp
:
break x:20 if strcmp(y, "hello") == 0
20
is line number, x
can be any filename and y
can be any variable.
React provides an interface for what you are trying to do via the ref
attribute. Assign a component a ref
, and its current
attribute will be your custom component:
class Parent extends React.Class {
constructor(props) {
this._child = React.createRef();
}
componentDidMount() {
console.log(this._child.current.someMethod()); // Prints 'bar'
}
render() {
return (
<div>
<Child ref={this._child} />
</div>
);
}
}
Note: This will only work if the child component is declared as a class, as per documentation found here: https://facebook.github.io/react/docs/refs-and-the-dom.html#adding-a-ref-to-a-class-component
Update 2019-04-01: Changed example to use a class and createRef
per latest React docs.
Update 2016-09-19: Changed example to use ref callback per guidance from the ref
String attribute docs.
You can also convert your array to a list and call remove on the list. You can then convert back to your array.
int[] numbers = {1, 3, 4, 9, 2};
var numbersList = numbers.ToList();
numbersList.Remove(4);
you can return 2 or more values to a function in VBA or any other visual basic stuff but you need to use the pointer method called Byref. See my example below. I will make a function to add and subtract 2 values say 5,6
sub Macro1
' now you call the function this way
dim o1 as integer, o2 as integer
AddSubtract 5, 6, o1, o2
msgbox o2
msgbox o1
end sub
function AddSubtract(a as integer, b as integer, ByRef sum as integer, ByRef dif as integer)
sum = a + b
dif = b - 1
end function
You could simply use the typeof
operator along with a ternary operator for short:
onsubmit="return typeof valid =='function' ? valid() : true;"
If it is a function we call it and return it's return value, otherwise just return true
Edit:
I'm not quite sure what you really want to do, but I'll try to explain what might be happening.
When you declare your onsubmit
code within your html, it gets turned into a function and thus its callable from the JavaScript "world". That means that those two methods are equivalent:
HTML: <form onsubmit="return valid();" />
JavaScript: myForm.onsubmit = function() { return valid(); };
These two will be both functions and both will be callable. You can test any of those using the typeof
operator which should yeld the same result: "function"
.
Now if you assign a string to the "onsubmit" property via JavaScript, it will remain a string, hence not callable. Notice that if you apply the typeof
operator against it, you'll get "string"
instead of "function"
.
I hope this might clarify a few things. Then again, if you want to know if such property (or any identifier for the matter) is a function and callable, the typeof
operator should do the trick. Although I'm not sure if it works properly across multiple frames.
Cheers
Necromancing.
IMHO, the existing answers leave much to be desired.
It's very simple:
Require is simply a (non-standard) function defined at global scope.
(window in browser, global in NodeJS).
Now, as such, to answer the question "what is require", we "simply" need to know what this function does.
This is perhaps best explained with code.
Here's a simple implementation by Michele Nasti, the code you can find on his github page.
Basically, let's call our minimalisc require function myRequire:
function myRequire(name)
{
console.log(`Evaluating file ${name}`);
if (!(name in myRequire.cache)) {
console.log(`${name} is not in cache; reading from disk`);
let code = fs.readFileSync(name, 'utf8');
let module = { exports: {} };
myRequire.cache[name] = module;
let wrapper = Function("require, exports, module", code);
wrapper(myRequire, module.exports, module);
}
console.log(`${name} is in cache. Returning it...`);
return myRequire.cache[name].exports;
}
myRequire.cache = Object.create(null);
window.require = myRequire;
const stuff = window.require('./main.js');
console.log(stuff);
Now you notice, the object "fs" is used here.
For simplicity's sake, Michele just imported the NodeJS fs module:
const fs = require('fs');
Which wouldn't be necessary.
So in the browser, you could make a simple implementation of require with a SYNCHRONOUS XmlHttpRequest:
const fs = {
file: `
// module.exports = \"Hello World\";
module.exports = function(){ return 5*3;};
`
, getFile(fileName: string, encoding: string): string
{
// https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests
let client = new XMLHttpRequest();
// client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
// open(method, url, async)
client.open("GET", fileName, false);
client.send();
if (client.status === 200)
return client.responseText;
return null;
}
, readFileSync: function (fileName: string, encoding: string): string
{
// this.getFile(fileName, encoding);
return this.file; // Example, getFile would fetch this file
}
};
Basically, what require thus does, is download a JavaScript-file, eval it in an anonymous namespace (aka Function), with the global parameters "require", "exports" and "module", and return the exports, meaning an object's public functions and properties.
Note that this evaluation is recursive: you require files, which themselfs can require files.
This way, all "global" variables used in your module are variables in the require-wrapper-function namespace, and don't pollute the global scope with unwanted variables.
Also, this way, you can reuse code without depending on namespaces, so you get "modularity" in JavaScript. "modularity" in quotes, because this is not exactly true, though, because you can still write window.bla, and hence still pollute the global scope... Also, this establishes a separation between private and public functions, the public functions being the exports.
Now instead of saying
module.exports = function(){ return 5*3;};
You can also say:
function privateSomething()
{
return 42:
}
function privateSomething2()
{
return 21:
}
module.exports = {
getRandomNumber: privateSomething
,getHalfRandomNumber: privateSomething2
};
and return an object.
Also, because your modules get evaluated in a function with parameters
"require", "exports" and "module", your modules can use the undeclared variables "require", "exports" and "module", which might be startling at first. The require parameter there is of course a ByVal pointer to the require function saved into a variable.
Cool, right ?
Seen this way, require looses its magic, and becomes simple.
Now, the real require-function will do a few more checks and quirks, of course, but this is the essence of what that boils down to.
Also, in 2020, you should use the ECMA implementations instead of require:
import defaultExport from "module-name";
import * as name from "module-name";
import { export1 } from "module-name";
import { export1 as alias1 } from "module-name";
import { export1 , export2 } from "module-name";
import { foo , bar } from "module-name/path/to/specific/un-exported/file";
import { export1 , export2 as alias2 , [...] } from "module-name";
import defaultExport, { export1 [ , [...] ] } from "module-name";
import defaultExport, * as name from "module-name";
import "module-name";
And if you need a dynamic non-static import (e.g. load a polyfill based on browser-type), there is the ECMA-import function/keyword:
var promise = import("module-name");
note that import is not synchronous like require.
Instead, import is a promise, so
var something = require("something");
becomes
var something = await import("something");
because import returns a promise (asynchronous).
So basically, unlike require, import replaces fs.readFileSync with fs.readFileAsync.
async readFileAsync(fileName, encoding)
{
const textDecoder = new TextDecoder(encoding);
// textDecoder.ignoreBOM = true;
const response = await fetch(fileName);
console.log(response.ok);
console.log(response.status);
console.log(response.statusText);
// let json = await response.json();
// let txt = await response.text();
// let blo:Blob = response.blob();
// let ab:ArrayBuffer = await response.arrayBuffer();
// let fd = await response.formData()
// Read file almost by line
// https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamDefaultReader/read#Example_2_-_handling_text_line_by_line
let buffer = await response.arrayBuffer();
let file = textDecoder.decode(buffer);
return file;
} // End Function readFileAsync
This of course requires the import-function to be async as well.
"use strict";
async function myRequireAsync(name) {
console.log(`Evaluating file ${name}`);
if (!(name in myRequireAsync.cache)) {
console.log(`${name} is not in cache; reading from disk`);
let code = await fs.readFileAsync(name, 'utf8');
let module = { exports: {} };
myRequireAsync.cache[name] = module;
let wrapper = Function("asyncRequire, exports, module", code);
await wrapper(myRequireAsync, module.exports, module);
}
console.log(`${name} is in cache. Returning it...`);
return myRequireAsync.cache[name].exports;
}
myRequireAsync.cache = Object.create(null);
window.asyncRequire = myRequireAsync;
async () => {
const asyncStuff = await window.asyncRequire('./main.js');
console.log(asyncStuff);
};
Even better, right ?
Well yea, except that there is no ECMA-way to dynamically import synchronously (without promise).
Now, to understand the repercussions, you absolutely might want to read up on promises/async-await here, if you don't know what that is.
But very simply put, if a function returns a promise, it can be "awaited":
function sleep (fn, par)
{
return new Promise((resolve) => {
// wait 3s before calling fn(par)
setTimeout(() => resolve(fn(par)), 3000)
})
}
var fileList = await sleep(listFiles, nextPageToken)
Which is nice way to make asynchronous code look synchronous.
Note that if you want to use async await in a function, that function must be declared async.
async function doSomethingAsync()
{
var fileList = await sleep(listFiles, nextPageToken)
}
And also please note that in JavaScript, there is no way to call an async function (blockingly) from a synchronous one (the ones you know). So if you want to use await (aka ECMA-import), all your code needs to be async, which most likely is a problem, if everything isn't already async...
An example of where this simplified implementation of require fails, is when you require a file that is not valid JavaScript, e.g. when you require css, html, txt, svg and images or other binary files.
And it's easy to see why:
If you e.g. put HTML into a JavaScript function body, you of course rightfully get
SyntaxError: Unexpected token '<'
because of Function("bla", "<doctype...")
Now, if you wanted to extend this to for example include non-modules, you could just check the downloaded file-contents with for code.indexOf("module.exports") == -1
, and then e.g. eval("jquery content") instead of Func (which works fine as long as you're in the browser). Since downloads with Fetch/XmlHttpRequests are subject to the same-origin-policy, and integrity is ensured by SSL/TLS, the use of eval here is rather harmless, provided you checked the JS files before you added them to your site, but that much should be standard-operating-procedure.
Note that there are several implementations of require-like functionality:
Also, we can use it following ways
To get only first
$cat_details = DB::table('an_category')->where('slug', 'people')->first();
To get by limit and offset
$top_articles = DB::table('an_pages')->where('status',1)->limit(30)->offset(0)->orderBy('id', 'DESC')->get();
$remaining_articles = DB::table('an_pages')->where('status',1)->limit(30)->offset(30)->orderBy('id', 'DESC')->get();
My personal choice is:
^\p{L}+[\p{L}\p{Pd}\p{Zs}']*\p{L}+$|^\p{L}+$
, Where:
^\p{L}+
- It should start with 1 or more letters.
[\p{Pd}\p{Zs}'\p{L}]*
- It can have letters, space character (including invisible), dash or hyphen characters and ' in any order 0 or more times.
\p{L}+$
- It should finish with 1 or more letters.
|^\p{L}+$
- Or it just should contain 1 or more letters (It is done to support single letter names).
Support for dots (full stops) was dropped, as in British English it can be dropped in Mr or Mrs, for example.
And here is a simple Send-MailMessage
example with username/password for anyone looking for just that
$secpasswd = ConvertTo-SecureString "PlainTextPassword" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ("username", $secpasswd)
Send-MailMessage -SmtpServer mysmptp -Credential $cred -UseSsl -From '[email protected]' -To '[email protected]' -Subject 'TEST'
Looks like you have an extra parenthesis.
The following portion is parsed as an assignment so the interpreter/compiler will look for a semi-colon or attempt to insert one if certain conditions are met.
foob_name = $this.attr('name').replace(/\[(\d+)\]/, function($0, $1) {
return '[' + (+$1 + 1) + ']';
})
Use two different patterns: [0-9]*
and [a-zA-Z]*
and split twice by each of them.
You can add a launch screen file that appears to work for multiple screen sizes. I just added the MainStoryboard as a launch screen file and that stopped the app from scaling. I think I will need to add a permanent launch screen later, but that got the native resolution up and working quickly. In Xcode, go to your target, general and add the launch screen file there.
That's the principle of a Pseudo-RNG. The numbers are not really random. They are generated using a deterministic algorithm, but depending on the seed, the sequence of generated numbers vary. Since you always use the same seed, you always get the same sequence.
I had a problem like this before, it was the gradle.properties file doesn't exist, only the gradle.properties.txt , so i went to my project folder and i copied & pasted the gradle.properties.txt file but without .txt extension then it finally worked.
Oracle has both the Date and the Timestamp data types.
According to Oracle documentation, there are differences in data size between Date and Timestamp, so when the intention is to have a Date only field it makes sense to show the Date formatting. Also, "It does not have fractional seconds or a time zone." - so it is not the best choice when timestamp information is required.
The Date field can be easily formatted to show the time component in the Oracle SQL Developer - Date query ran in PL/SQL Developer shows time, but does not show in Oracle SQL Developer. But it won't show the fractional seconds or the time zone - for this you need Timestamp data type.
Or, if you are looking for simple collection of errors for your apps.. here is my implementation of this:
public override void OnActionExecuting(HttpActionContext actionContext)
{
var modelState = actionContext.ModelState;
if (!modelState.IsValid)
{
var errors = new List<string>();
foreach (var state in modelState)
{
foreach (var error in state.Value.Errors)
{
errors.Add(error.ErrorMessage);
}
}
var response = new { errors = errors };
actionContext.Response = actionContext.Request
.CreateResponse(HttpStatusCode.BadRequest, response, JsonMediaTypeFormatter.DefaultMediaType);
}
}
Error Message Response will look like:
{ "errors": [ "Please enter a valid phone number (7+ more digits)", "Please enter a valid e-mail address" ] }
There is an important bit that is not mentioned in the article to which you linked and that is flex-basis
. By default flex-basis
is auto
.
From the spec:
If the specified flex-basis is auto, the used flex basis is the value of the flex item’s main size property. (This can itself be the keyword auto, which sizes the flex item based on its contents.)
Each flex item has a flex-basis
which is sort of like its initial size. Then from there, any remaining free space is distributed proportionally (based on flex-grow
) among the items. With auto
, that basis is the contents size (or defined size with width
, etc.). As a result, items with bigger text within are being given more space overall in your example.
If you want your elements to be completely even, you can set flex-basis: 0
. This will set the flex basis to 0 and then any remaining space (which will be all space since all basises are 0) will be proportionally distributed based on flex-grow
.
li {
flex-grow: 1;
flex-basis: 0;
/* ... */
}
This diagram from the spec does a pretty good job of illustrating the point.
And here is a working example with your fiddle.
You can install pywin32 wheel packages from PYPI with PIP by pointing to this package: https://pypi.python.org/pypi/pypiwin32 No need to worry about first downloading the package, just use pip:
pip install pypiwin32
Currently I think this is "the easiest" way to get in working :) Hope this helps.
None of the above solutions worked for me, I found an article that explained the issue. The security protocols on the system were deprecated and therefore displayed an error message that no match was found for the ProviderPackage.
Here is a the basic steps for upgrading your security protocols:
Run both cmdlets to set .NET Framework strong cryptography registry keys. After that, restart PowerShell and check if the security protocol TLS 1.2 is added. As of last, install the PowerShellGet module.
The first cmdlet is to set strong cryptography on 64 bit .Net Framework (version 4 and above).
[PS] C:\>Set-ItemProperty -Path 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NetFramework\v4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type DWord
1
[PS] C:\>Set-ItemProperty -Path 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NetFramework\v4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type DWord
The second cmdlet is to set strong cryptography on 32 bit .Net Framework (version 4 and above).
[PS] C:\>Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\.NetFramework\v4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type DWord
1
[PS] C:\>Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\.NetFramework\v4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type DWord
Restart Powershell and check for supported security protocols.
[PS] C:\>[Net.ServicePointManager]::SecurityProtocol
Tls, Tls11, Tls12
1
2
[PS] C:\>[Net.ServicePointManager]::SecurityProtocol
Tls, Tls11, Tls12
Run the command Install-Module PowershellGet -Force and press Y to install NuGet provider, follow with Enter.
[PS] C:\>Install-Module PowershellGet -Force
NuGet provider is required to continue
PowerShellGet requires NuGet provider version '2.8.5.201' or newer to interact with NuGet-based repositories. The NuGet provider must be available in 'C:\Program Files\PackageManagement\ProviderAssemblies' or
'C:\Users\administrator.EXOIP\AppData\Local\PackageManagement\ProviderAssemblies'. You can also install the NuGet provider by running 'Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force'. Do you want PowerShellGet to install
and import the NuGet provider now?
[Y] Yes [N] No [S] Suspend [?] Help (default is "Y"): Y
[PS] C:\>Install-Module PowershellGet -Force
NuGet provider is required to continue
PowerShellGet requires NuGet provider version '2.8.5.201' or newer to interact with NuGet-based repositories. The NuGet provider must be available in 'C:\Program Files\PackageManagement\ProviderAssemblies' or
'C:\Users\administrator.EXOIP\AppData\Local\PackageManagement\ProviderAssemblies'. You can also install the NuGet provider by running 'Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force'. Do you want PowerShellGet to install
and import the NuGet provider now?
[Y] Yes [N] No [S] Suspend [?] Help (default is "Y"): Y
For anyone that stumbles upon this page, none of the solutions here worked for me. I found this is the way to do it (in a batch file):
@for /f "skip=1" %%p in ('wmic cpu get loadpercentage /VALUE') do (
for /F "tokens=2 delims==" %%J in ("%%p") do echo %%J
)
I also had need for this and I created the following extension method for it:
public static class RegexExtensions
{
public static string ReplaceGroup(
this Regex regex, string input, string groupName, string replacement)
{
return regex.Replace(
input,
m =>
{
var group = m.Groups[groupName];
var sb = new StringBuilder();
var previousCaptureEnd = 0;
foreach (var capture in group.Captures.Cast<Capture>())
{
var currentCaptureEnd =
capture.Index + capture.Length - m.Index;
var currentCaptureLength =
capture.Index - m.Index - previousCaptureEnd;
sb.Append(
m.Value.Substring(
previousCaptureEnd, currentCaptureLength));
sb.Append(replacement);
previousCaptureEnd = currentCaptureEnd;
}
sb.Append(m.Value.Substring(previousCaptureEnd));
return sb.ToString();
});
}
}
Usage:
var input = @"[assembly: AssemblyFileVersion(""2.0.3.0"")][assembly: AssemblyFileVersion(""2.0.3.0"")]";
var regex = new Regex(@"AssemblyFileVersion\(""(?<version>(\d+\.?){4})""\)");
var result = regex.ReplaceGroup(input , "version", "1.2.3");
Result:
[assembly: AssemblyFileVersion("1.2.3")][assembly: AssemblyFileVersion("1.2.3")]
Starting from tslint v5.8.0
you can set an exclude
property under your linterOptions
key in your tslint.json
file:
{
"extends": "tslint:latest",
"linterOptions": {
"exclude": [
"bin",
"**/__test__",
"lib/*generated.js"
]
}
}
More information on this here.
To get the screen resolution use should use Javascript instead of CSS:
Use screen.height
for height and screen.width
for width.
Ditch FileWriter
and FileReader
, which are useless exactly because they do not allow you to specify the encoding. Instead, use
new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)
and
new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8);
Your primary question has been answered above. I just wanted to point out that the regex you're using has a bug. It will also succeed on foo-domain.com
which is not a subdomain of domain.com
What you really want is this:
/(^|\.)domain\.com$/
If you are using AngularJS version 1.X you could use the $log service instead of using console.log directly.
Simple service for logging. Default implementation safely writes the message into the browser's console (if present).
https://docs.angularjs.org/api/ng/service/$log
So if you have something similar to
angular.module('logExample', [])
.controller('LogController', ['$scope', function($scope) {
console.log('Hello World!');
}]);
you can replace it with
angular.module('logExample', [])
.controller('LogController', ['$scope', '$log', function($scope, $log) {
$log.log('Hello World!');
}]);
Angular 2+ does not have any built-in log service.
I don't agree with any solution here, as they are too permissive. This is not normally what you want when parsing a string.
So here the solution I'm using:
def to_bool(bool_str):
"""Parse the string and return the boolean value encoded or raise an exception"""
if isinstance(bool_str, basestring) and bool_str:
if bool_str.lower() in ['true', 't', '1']: return True
elif bool_str.lower() in ['false', 'f', '0']: return False
#if here we couldn't parse it
raise ValueError("%s is no recognized as a boolean value" % bool_str)
And the results:
>>> [to_bool(v) for v in ['true','t','1','F','FALSE','0']]
[True, True, True, False, False, False]
>>> to_bool("")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 8, in to_bool
ValueError: '' is no recognized as a boolean value
Just to be clear because it looks as if my answer offended somebody somehow:
The point is that you don't want to test for only one value and assume the other. I don't think you always want to map Absolutely everything to the non parsed value. That produces error prone code.
So, if you know what you want code it in.
If you are using SharePoint and angular then do it like below:
<a ng-href="{{item.LinkTo.Url}}" target="_blank" ng-bind="item.Title;" ></a>
where LinkTo and Title is SharePoint Column.
You're passing the same model to the partial view as is being passed to the main view, and they are different types. The model is a DbSet
of Note
s, where you need to pass in a single Note
.
You can do this by adding a parameter, which I'm guessing as it's the create form would be a new Note
@Html.Partial("_CreateNote", new QuickNotes.Models.Note())
You have to add the google-play-services-lib
as a library-project. They updated the SDK. There are several tutorials around. For Eclipse it is easy:
Right click project -> properties -> Android
For more detailed walkthroughs:
If you're in a method bound to an event, simply return false:
@Component({
(...)
template: `
<a href="/test.html" (click)="doSomething()">Test</a>
`
})
export class MyComp {
doSomething() {
(...)
return false;
}
}
Refer https://docs.python.org/2/tutorial/controlflow.html#unpacking-argument-lists
dt = datetime.datetime(*t[:7])
The issue you are encountering is a documented feature of get_or_create
.
When using keyword arguments other than "defaults" the return value of get_or_create
is an instance. That's why it is showing you the parens in the return value.
you could use customer.source = Source.objects.get_or_create(name="Website")[0]
to get the correct value.
Here is a link for the documentation: http://docs.djangoproject.com/en/dev/ref/models/querysets/#get-or-create-kwargs
It's as easy as:
delete object.keyname;
or
delete object["keyname"];
For this example you will need to create your own type, that would be an array. Then you create a bigger array which elements are of type you have just created.
To run my example you will need to fill columns A and B in Sheet1 with some values. Then run test(). It will read first two rows and add the values to the BigArr. Then it will check how many rows of data you have and read them all, from the place it has stopped reading, i.e., 3rd row.
Tested in Excel 2007.
Option Explicit
Private Type SmallArr
Elt() As Variant
End Type
Sub test()
Dim x As Long, max_row As Long, y As Long
'' Define big array as an array of small arrays
Dim BigArr() As SmallArr
y = 2
ReDim Preserve BigArr(0 To y)
For x = 0 To y
ReDim Preserve BigArr(x).Elt(0 To 1)
'' Take some test values
BigArr(x).Elt(0) = Cells(x + 1, 1).Value
BigArr(x).Elt(1) = Cells(x + 1, 2).Value
Next x
'' Write what has been read
Debug.Print "BigArr size = " & UBound(BigArr) + 1
For x = 0 To UBound(BigArr)
Debug.Print BigArr(x).Elt(0) & " | " & BigArr(x).Elt(1)
Next x
'' Get the number of the last not empty row
max_row = Range("A" & Rows.Count).End(xlUp).Row
'' Change the size of the big array
ReDim Preserve BigArr(0 To max_row)
Debug.Print "new size of BigArr with old data = " & UBound(BigArr)
'' Check haven't we lost any data
For x = 0 To y
Debug.Print BigArr(x).Elt(0) & " | " & BigArr(x).Elt(1)
Next x
For x = y To max_row
'' We have to change the size of each Elt,
'' because there are some new for,
'' which the size has not been set, yet.
ReDim Preserve BigArr(x).Elt(0 To 1)
'' Take some test values
BigArr(x).Elt(0) = Cells(x + 1, 1).Value
BigArr(x).Elt(1) = Cells(x + 1, 2).Value
Next x
'' Check what we have read
Debug.Print "BigArr size = " & UBound(BigArr) + 1
For x = 0 To UBound(BigArr)
Debug.Print BigArr(x).Elt(0) & " | " & BigArr(x).Elt(1)
Next x
End Sub
Using the Elastic search DSL API, you may hit the same error with
s = Search(using=client, index="my-index") \
.query("match", category.keyword="Musician")
You can solve it by doing:
s = Search(using=client, index="my-index") \
.query({"match": {"category.keyword":"Musician/Band"}})
I came here looking for exporting blob into file with least effort. CLR functions is not something what I'd call least effort. Here described lazier one, using OLE Automation:
declare @init int
declare @file varbinary(max) = CONVERT(varbinary(max), N'your blob here')
declare @filepath nvarchar(4000) = N'c:\temp\you file name here.txt'
EXEC sp_OACreate 'ADODB.Stream', @init OUTPUT; -- An instace created
EXEC sp_OASetProperty @init, 'Type', 1;
EXEC sp_OAMethod @init, 'Open'; -- Calling a method
EXEC sp_OAMethod @init, 'Write', NULL, @file; -- Calling a method
EXEC sp_OAMethod @init, 'SaveToFile', NULL, @filepath, 2; -- Calling a method
EXEC sp_OAMethod @init, 'Close'; -- Calling a method
EXEC sp_OADestroy @init; -- Closed the resources
You'll potentially need to allow to run OA stored procedures on server (and then turn it off, when you're done):
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ole Automation Procedures', 1;
GO
RECONFIGURE;
GO
You can compute the LCM of more than two numbers by iteratively computing the LCM of two numbers, i.e.
lcm(a,b,c) = lcm(a,lcm(b,c))
Use below code to generate files on fly..
<? //Generate text file on the fly
header("Content-type: text/plain");
header("Content-Disposition: attachment; filename=savethis.txt");
// do your Db stuff here to get the content into $content
print "This is some text...\n";
print $content;
?>
I get this one all the time. It means that the user started to download a file, and then it either failed, or they cancelled it.
To reproduce the exception try do this yourself - however I'm unaware of any ways to prevent it (except for handling this specific exception only).
You need to decide what the best way forward is depending on your app.
Here is a simple solution without any loops or any hassle which will allow you to create random string with characters, numbers or even with special symbols.
$randomNum = substr(str_shuffle("0123456789"), 0, $x);
where $x
can be number of digits
Eg.
substr(str_shuffle("0123456789"), 0, 5);
Results after a couple of executions
98450
79324
23017
04317
26479
You can use the same code to generate random string also, like this
$randomNum=substr(str_shuffle("0123456789abcdefghijklmnopqrstvwxyzABCDEFGHIJKLMNOPQRSTVWXYZ"), 0, $x);
Results with $x = 11
FgHmqpTR3Ox
O9BsNgcPJDb
1v8Aw5b6H7f
haH40dmAxZf
0EpvHL5lTKr
I would recommend using mingw/msys as a development environment. Especially if you are porting simple console programs. Msys implements a Unix-like shell on Windows, and mingw is a port of the GNU compiler collection (GCC) and other GNU build tools to the Windows platform. It is an open-source project, and well-suited to the task. I currently use it to build utility programs and console applications for Windows XP, and it most certainly has that unistd.h
header you are looking for.
The install procedure can be a little bit tricky, but I found that the best place to start is in MSYS.
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.
If you want to change the default for "git pull" and "git fetch" to only fetch specific branches then you can edit .git/config so that the remote config looks like:
[remote "origin"]
fetch = +refs/heads/master:refs/remotes/origin/master
This will only fetch master from origin by default. See for more info: https://git-scm.com/book/en/v2/Git-Internals-The-Refspec
EDIT: Just realized this is the same thing that the -t option does for git remote add. At least this is a nice way to do it after the remote is added if you don't want ot delete the remote and add it again using -t.
For me it was some other git URL placed in config file, so I did change it manually:
[remote "origin"]
url = [email protected]:prat3ik/my-project.git
And it was working!!
I used: "\n\r" - it only works in double quotes though.
var fvalue = "foo";
var svalue = "bar";
alert("My first value is: " + fvalue + "\n\rMy second value is: " + svalue);
will alert as:
My first value is: foo
My second value is: bar
Thankyou Frank.i got the idea. Here is the working code.
Option Explicit
Private Sub CommandButton1_Click()
Dim directory As String, fileName As String, sheet As Worksheet, total As Integer
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
.Title = "Please select the file."
.Filters.Clear
.Filters.Add "Excel 2003", "*.xls?"
If .Show = True Then
fileName = Dir(.SelectedItems(1))
End If
End With
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Workbooks.Open (fileName)
For Each sheet In Workbooks(fileName).Worksheets
total = Workbooks("import-sheets.xlsm").Worksheets.Count
Workbooks(fileName).Worksheets(sheet.Name).Copy _
after:=Workbooks("import-sheets.xlsm").Worksheets(total)
Next sheet
Workbooks(fileName).Close
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
To solve this problem first make sure that your java software should be 32bit version if it is 64 bit version clearly it will show the mismatch error so try to re-install 32bit of java version And execute the java program in the command of c:\windows\sysWOW64\odbcad32.exe (easiest to copy and paste into run dialog) that's enough your program definitely work
[NonAction]
private ActionResult CRUD(someModel entity)
{
try
{
//you business logic here
return View(entity);
}
catch (Exception exp)
{
ModelState.AddModelError("", exp.InnerException.Message);
Response.StatusCode = 350;
return someerrohandilingactionresult(entity, actionType);
}
//Retrun appropriate message or redirect to proper action
return RedirectToAction("Index");
}
The simple option is just to set the forms's AcceptButton to the button you want pressed (usually "OK" etc):
TextBox tb = new TextBox();
Button btn = new Button { Dock = DockStyle.Bottom };
btn.Click += delegate { Debug.WriteLine("Submit: " + tb.Text); };
Application.Run(new Form { AcceptButton = btn, Controls = { tb, btn } });
If this isn't an option, you can look at the KeyDown event etc, but that is more work...
TextBox tb = new TextBox();
Button btn = new Button { Dock = DockStyle.Bottom };
btn.Click += delegate { Debug.WriteLine("Submit: " + tb.Text); };
tb.KeyDown += (sender,args) => {
if (args.KeyCode == Keys.Return)
{
btn.PerformClick();
}
};
Application.Run(new Form { Controls = { tb, btn } });
TIME_WAIT might not be the culprit.
int listen(int sockfd, int backlog);
According to Unix Network Programming Volume1, backlog is defined to be the sum of completed connection queue and incomplete connection queue.
Let's say the backlog is 5. If you have 3 completed connections (ESTABLISHED state), and 2 incomplete connections (SYN_RCVD state), and there is another connect request with SYN. The TCP stack just ignores the SYN packet, knowing it'll be retransmitted some other time. This might be causing the degradation.
At least that's what I've been reading. ;)
You would simply need to do this in your onClick
:
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Alert message to be shown");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
I don't know from where you saw that you need DialogFragment for simply showing an alert.
Hope this helps.
You are getting this error because the value cannot be found in the range. String or integer doesn't matter. Best thing to do in my experience is to do a check first to see if the value exists.
I used CountIf below, but there is lots of different ways to check existence of a value in a range.
Public Sub test()
Dim rng As Range
Dim aNumber As Long
aNumber = 666
Set rng = Sheet5.Range("B16:B615")
If Application.WorksheetFunction.CountIf(rng, aNumber) > 0 Then
rowNum = Application.WorksheetFunction.Match(aNumber, rng, 0)
Else
MsgBox aNumber & " does not exist in range " & rng.Address
End If
End Sub
ALTERNATIVE WAY
Public Sub test()
Dim rng As Range
Dim aNumber As Variant
Dim rowNum As Long
aNumber = "2gg"
Set rng = Sheet5.Range("B1:B20")
If Not IsError(Application.Match(aNumber, rng, 0)) Then
rowNum = Application.Match(aNumber, rng, 0)
MsgBox rowNum
Else
MsgBox "error"
End If
End Sub
OR
Public Sub test()
Dim rng As Range
Dim aNumber As Variant
Dim rowNum As Variant
aNumber = "2gg"
Set rng = Sheet5.Range("B1:B20")
rowNum = Application.Match(aNumber, rng, 0)
If Not IsError(rowNum) Then
MsgBox rowNum
Else
MsgBox "error"
End If
End Sub
I use codeigniter 3+. I had the same problem and in my case I changed model file name starting from uppser case.
Logon_model.php
Android Studio comes with Gradle, but it does not have the command line gradle functionality.
First note that with numpy's broadcasting operations it's usually not necessary to duplicate rows and columns. See this and this for descriptions.
But to do this, repeat and newaxis are probably the best way
In [12]: x = array([1,2,3])
In [13]: repeat(x[:,newaxis], 3, 1)
Out[13]:
array([[1, 1, 1],
[2, 2, 2],
[3, 3, 3]])
In [14]: repeat(x[newaxis,:], 3, 0)
Out[14]:
array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3]])
This example is for a row vector, but applying this to a column vector is hopefully obvious. repeat seems to spell this well, but you can also do it via multiplication as in your example
In [15]: x = array([[1, 2, 3]]) # note the double brackets
In [16]: (ones((3,1))*x).transpose()
Out[16]:
array([[ 1., 1., 1.],
[ 2., 2., 2.],
[ 3., 3., 3.]])
Had the same problem. A colleague solved this with jQuery.Globalize.
<script src="/Scripts/jquery.validate.js" type="text/javascript"></script>
<script src="/Scripts/jquery.globalize/globalize.js" type="text/javascript"></script>
<script src="/Scripts/jquery.globalize/cultures/globalize.culture.nl.js"></script>
<script type="text/javascript">
var lang = 'nl';
$(function () {
Globalize.culture(lang);
});
// fixing a weird validation issue with dates (nl date notation) and Google Chrome
$.validator.methods.date = function(value, element) {
var d = Globalize.parseDate(value);
return this.optional(element) || !/Invalid|NaN/.test(d);
};
</script>
I am using jQuery Datepicker for selecting the date.
With template literals, you can use multiple spaces or multi-line strings and string interpolation. Template Literals are a new ES2015 / ES6 feature that allows you to work with strings. The syntax is very simple, just use backticks instead of single or double quotes:
let a = `something something`;
and to make multiline strings just press enter to create a new line, with no special characters:
let a = `something
something`;
The results are exactly the same as you write in the string.
I've written a library that is up-to-date, since all the other answers are outdated:
Simply put, you need to rewrite all of your database connections and queries.
You are using mysql_*
functions which are now deprecated and will be removed from PHP in the future. So you need to start using MySQLi or PDO instead, just as the error notice warned you.
A basic example of using PDO (without error handling):
<?php
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
$result = $db->exec("INSERT INTO table(firstname, lastname) VAULES('John', 'Doe')");
$insertId = $db->lastInsertId();
?>
A basic example of using MySQLi (without error handling):
$db = new mysqli($DBServer, $DBUser, $DBPass, $DBName);
$result = $db->query("INSERT INTO table(firstname, lastname) VAULES('John', 'Doe')");
Here's a handy little PDO tutorial to get you started. There are plenty of others, and ones about the PDO alternative, MySQLi.
Basically, you need to catch the OperationCanceledException
and check the state of the cancellation token that was passed to SendAsync
(or GetAsync
, or whatever HttpClient
method you're using):
IsCancellationRequested
is true), it means the request really was canceledOf course, this isn't very convenient... it would be better to receive a TimeoutException
in case of timeout. I propose a solution here based on a custom HTTP message handler: Better timeout handling with HttpClient
This is an old question, but comes out high in my Google search for 'perl merge hashes' - and yet it does not mention the very helpful CPAN module Hash::Merge
This is answered in some of the answers to Can't find how to use HttpContent as well as in this blog post.
In summary, you can't directly set up an instance of HttpContent
because it is an abstract class. You need to use one the classes derived from it depending on your need. Most likely StringContent
, which lets you set the string value of the response, the encoding, and the media type in the constructor. See: http://msdn.microsoft.com/en-us/library/system.net.http.stringcontent.aspx
Another approach when you have many updates would be to use COALESCE:
UPDATE [DATABASE].[dbo].[TABLE_NAME]
SET
[ABC] = COALESCE(@ABC, [ABC]),
[ABCD] = COALESCE(@ABCD, [ABCD])
Find Plunker for Formatting Credit Card Numbers using angularjs directive. Format Card Numbers in xxxxxxxxxxxx3456 Fromat.
angular.module('myApp', [])
.directive('maskInput', function() {
return {
require: "ngModel",
restrict: "AE",
scope: {
ngModel: '=',
},
link: function(scope, elem, attrs) {
var orig = scope.ngModel;
var edited = orig;
scope.ngModel = edited.slice(4).replace(/\d/g, 'x') + edited.slice(-4);
elem.bind("blur", function() {
var temp;
orig = elem.val();
temp = elem.val();
elem.val(temp.slice(4).replace(/\d/g, 'x') + temp.slice(-4));
});
elem.bind("focus", function() {
elem.val(orig);
});
}
};
})
.controller('myCtrl', ['$scope', '$interval', function($scope, $interval) {
$scope.creditCardNumber = "1234567890123456";
}]);
Do something like this:
<script>
function changeColor(id)
{
document.getElementById(id).style.color = "#ff0000"; // forecolor
document.getElementById(id).style.backgroundColor = "#ff0000"; // backcolor
}
</script>
<div id="myid">Hello There !!</div>
<a href="#" onclick="changeColor('myid'); return false;">Change Color</a>
Check this out xmlvm I think this is possible. May be can also check this video
There is no efficient way in the sense of algorithmic complexity (an algorithm with polynomial complexity) known in science by now. So iterating until the square root as already suggested is mostly as good as you can be.
Mainly because of this, a large part of the currently used cryptography is based on the assumption that it is very time consuming to compute a prime factorization of any given integer.
1) Note that it is considered insecure to have the .htpasswd
file below the server root.
2) The docs say this about relative paths, so it looks you're out of luck:
File-path is the path to the user file. If it is not absolute (i.e., if it doesn't begin with a slash), it is treated as relative to the ServerRoot.
3) While the answers recommending the use of environment variables work perfectly fine, I would prefer to put a placeholder in the .htaccess
file, or have different versions in my codebase, and have the deployment process set it all up (i. e. replace placeholders or rename / move the appropriate file).
On Java projects, I use Maven to do this type of work, on, say, PHP projects, I like to have a build.sh and / or install.sh shell script that tunes the deployed files to their environment. This decouples your codebase from the specifics of its target environment (i. e. its environment variables and configuration parameters). In general, the application should adapt to the environment, if you do it the other way around, you might run into problems once the environment also has to cater for different applications, or for completely unrelated, system-specific requirements.
With New-Item you can add the Force parameter
New-Item -Force -ItemType directory -Path foo
Or the ErrorAction parameter
New-Item -ErrorAction Ignore -ItemType directory -Path foo
TL;DR
Java caches boxed Integer instances from -128
to 127
. Since you are using ==
to compare objects references instead of values, only cached objects will match. Either work with long
unboxed primitive values or use .equals()
to compare your Long
objects.
Long (pun intended) version
Why there is problem in comparing Long variable with value greater than 127? If the data type of above variable is primitive (long) then code work for all values.
Java caches Integer objects instances from the range -128 to 127. That said:
127
(cached), the same object instance will be pointed by all references. (N variables, 1 instance)128
(not cached), you will have an object instance pointed by every reference. (N variables, N instances)That's why this:
Long val1 = 127L;
Long val2 = 127L;
System.out.println(val1 == val2);
Long val3 = 128L;
Long val4 = 128L;
System.out.println(val3 == val4);
Outputs this:
true
false
For the 127L value, since both references (val1 and val2) point to the same object instance in memory (cached), it returns true
.
On the other hand, for the 128 value, since there is no instance for it cached in memory, a new one is created for any new assignments for boxed values, resulting in two different instances (pointed by val3 and val4) and returning false
on the comparison between them.
That happens solely because you are comparing two Long
object references, not long
primitive values, with the ==
operator. If it wasn't for this Cache mechanism, these comparisons would always fail, so the real problem here is comparing boxed values with ==
operator.
Changing these variables to primitive long
types will prevent this from happening, but in case you need to keep your code using Long
objects, you can safely make these comparisons with the following approaches:
System.out.println(val3.equals(val4)); // true
System.out.println(val3.longValue() == val4.longValue()); // true
System.out.println((long)val3 == (long)val4); // true
(Proper null checking is necessary, even for castings)
IMO, it's always a good idea to stick with .equals() methods when dealing with Object comparisons.
Reference links:
sed 's/^.\{,5\}//' file.dat
worked like a charm for me
it turns out that with python 2.5.2, del l[:]
is slightly slower than l[:] = []
by 1.1 usec.
$ python -mtimeit "l=list(range(1000))" "b=l[:];del b[:]"
10000 loops, best of 3: 29.8 usec per loop
$ python -mtimeit "l=list(range(1000))" "b=l[:];b[:] = []"
10000 loops, best of 3: 28.7 usec per loop
$ python -V
Python 2.5.2
$(document).ready(function() {_x000D_
$("a").click(function(event) {_x000D_
var myClass = $(this).attr("class");_x000D_
var myId = $(this).attr('id');_x000D_
alert(myClass + " " + myId);_x000D_
});_x000D_
})
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<a href="#" id="kana1" class="konbo">click me 1</a>_x000D_
<a href="#" id="kana2" class="kinta">click me 2</a>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
This works for me. There is no event.target.class function in jQuery.
If you just want see the output of the process running from within the container, you can do a simple docker container logs -f <container id>
.
The -f
flag makes it so that the output of the container is followed
and updated in real-time. Very useful for debugging or monitoring.
June 3, 2020 (All answers didn't worked, you can try this solution I used. Just for TimeField)
Use simple Charfield
for time fields (start and end in this example) in forms.
forms.py
we can use Form
or ModelForm
here.
class TimeSlotForm(forms.ModelForm):
start = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'HH:MM'}))
end = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'HH:MM'}))
class Meta:
model = TimeSlots
fields = ('start', 'end', 'provider')
Convert string input into time object in views.
import datetime
def slots():
if request.method == 'POST':
form = create_form(request.POST)
if form.is_valid():
slot = form.save(commit=False)
start = form.cleaned_data['start']
end = form.cleaned_data['end']
start = datetime.datetime.strptime(start, '%H:%M').time()
end = datetime.datetime.strptime(end, '%H:%M').time()
slot.start = start
slot.end = end
slot.save()
you can try:
services:
nameis:
container_name: hi_my
build: .
image: hi_my_nameis:v1.0.0
Here, we can do this way as well:
//category [@name='category name']/author[contains(text(),'authorname')]
OR
//category [@name='category name']//author[contains(text(),'authorname')]
To Learn XPATH in detail please visit- selenium xpath in detail
svn revert . -R
svn status | rm -rf $(awk '/^?/{$1 = ""; print $0}')
The -rf
may/should look scary at first, but once understood it will not be for these reasons:
rm
-rf
is required, else these directories will not be removedsvn revert . -R && svn status | rm -rf $(awk '/^?/{$1 = ""; print $0}')
Add permanent alias to your .bash_aliases
alias svn.HardReset='read -p "destroy all local changes?[y/N]" && [[ $REPLY =~ ^[yY] ]] && svn revert . -R && rm -rf $(awk -f <(echo "/^?/{print \$2}") <(svn status) ;)'
Object AccountObject = _dbContext.Accounts
.Join(_dbContext.Users, acc => acc.AccountId, usr => usr.AccountId, (acc, usr) => new { acc, usr })
.Where(x => x.usr.EmailAddress == key1)
.Where(x => x.usr.Hash == key2)
.Select(x => new { AccountId = x.acc.AccountId, Name = x.acc.Name })
.SingleOrDefault();
Date dateAfterOneMonth = new DateTime(System.currentTimeMillis()).plusMonths(1).toDate();
I meet the same problem today with OkHttp client to GET a https based url. It was caused by Https protocol version and Cipher method mismatch between server side and client side.
1) check your website https Protocol version and Cipher method.openssl>s_client -connect your_website.com:443 -showcerts
You will get many detail info, the key info is listed as follows:
SSL-Session:
Protocol : TLSv1
Cipher : RC4-SHA
2) config your http client, for example, in OkHttp client case:
@Test()
public void testHttpsByOkHttp() {
ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
.tlsVersions(TlsVersion.TLS_1_0) //protocol version
.cipherSuites(
CipherSuite.TLS_RSA_WITH_RC4_128_SHA, //cipher method
CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256)
.build();
OkHttpClient client = new OkHttpClient();
client.setConnectionSpecs(Collections.singletonList(spec));
Request request = new Request.Builder().url("https://your_website.com/").build();
try {
Response response = client.newCall(request).execute();
if(response.isSuccessful()){
logger.debug("result= {}", response.body().string());
}
} catch (IOException e) {
e.printStackTrace();
}
}
This will get what we want.
Are you keeping references to variables that you no longer need (e.g. data from the previous simulations)? If so, you have a memory leak. You just need to find where that is happening and make sure that you remove the references to the variables when they are no longer needed (this would automatically happen if they go out of scope).
If you actually need all that data from previous simulations in memory, you need to increase the heap size or change your algorithm.
apache commons lang has a class SystemUtils.java you can use :
SystemUtils.IS_OS_LINUX
SystemUtils.IS_OS_WINDOWS
Your major problem is not the stuff to the right of the decimal, it is the stuff to the left. The two values in your type declaration are precision and scale.
From MSDN: "Precision is the number of digits in a number. Scale is the number of digits to the right of the decimal point in a number. For example, the number 123.45 has a precision of 5 and a scale of 2."
If you specify (10, 4), that means you can only store 6 digits to the left of the decimal, or a max number of 999999.9999. Anything bigger than that will cause an overflow.
There's also git whatchanged
, which is more low level than git log
NAME
git-whatchanged - Show logs with difference each commit introduces
It outputs the commit summary with a list of files beneath it with their modes and if there added(A
), deleted(D
) or modified(M
);
$ git whatchanged f31a441398fb7834fde24c5b0c2974182a431363
Would give something like:
commit f31a441398fb7834fde24c5b0c2974182a431363
Author: xx <[email protected]>
Date: Tue Sep 29 17:23:22 2015 +0200
added fb skd and XLForm
:000000 100644 0000000... 90a20d7... A Pods/Bolts/Bolts/Common/BFCancellationToken.h
:000000 100644 0000000... b5006d0... A Pods/Bolts/Bolts/Common/BFCancellationToken.m
:000000 100644 0000000... 3e7b711... A Pods/Bolts/Bolts/Common/BFCancellationTokenRegistration.h
:000000 100644 0000000... 9c8a7ae... A Pods/Bolts/Bolts/Common/BFCancellationTokenRegistration.m
:000000 100644 0000000... bd6e7a1... A Pods/Bolts/Bolts/Common/BFCancellationTokenSource.h
:000000 100644 0000000... 947f725... A Pods/Bolts/Bolts/Common/BFCancellationTokenSource.m
:000000 100644 0000000... cf7dcdf... A Pods/Bolts/Bolts/Common/BFDefines.h
:000000 100644 0000000... 02af9ba... A Pods/Bolts/Bolts/Common/BFExecutor.h
:000000 100644 0000000... 292e27c... A Pods/Bolts/Bolts/Common/BFExecutor.m
:000000 100644 0000000... 827071d... A Pods/Bolts/Bolts/Common/BFTask.h
...
I know this answer doesn't really match "with no extraneous information.", but I still think this list is more useful then just the filenames.
If you are using Angular 2 (apparently it also works for Angular 4 too), you can use the following to round to two decimal places{{ exampleNumber | number : '1.2-2' }}
, as in:
<ion-input value="{{ exampleNumber | number : '1.2-2' }}"></ion-input>
BREAKDOWN
'1.2-2'
means {minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}
:
The se argument from the example also isn't in the help or online documentation.
When 'se' in geom_smooth is set 'FALSE', the error shading region is not visible
Use character classes. A character class beginning with caret will match anything not in the class.
[^,;]
IMHO, most arguments against recursive locks (which are what I use 99.9% of the time over like 20 years of concurrent programming) mix the question if they are good or bad with other software design issues, which are quite unrelated. To name one, the "callback" problem, which is elaborated on exhaustively and without any multithreading related point of view, for example in the book Component software - beyond Object oriented programming.
As soon as you have some inversion of control (e.g. events fired), you face re-entrance problems. Independent of whether there are mutexes and threading involved or not.
class EvilFoo {
std::vector<std::string> data;
std::vector<std::function<void(EvilFoo&)> > changedEventHandlers;
public:
size_t registerChangedHandler( std::function<void(EvilFoo&)> handler) { // ...
}
void unregisterChangedHandler(size_t handlerId) { // ...
}
void fireChangedEvent() {
// bad bad, even evil idea!
for( auto& handler : changedEventHandlers ) {
handler(*this);
}
}
void AddItem(const std::string& item) {
data.push_back(item);
fireChangedEvent();
}
};
Now, with code like the above you get all error cases, which would usually be named in the context of recursive locks - only without any of them. An event handler can unregister itself once it has been called, which would lead to a bug in a naively written fireChangedEvent()
. Or it could call other member functions of EvilFoo
which cause all sorts of problems. The root cause is re-entrance.
Worst of all, this could not even be very obvious as it could be over a whole chain of events firing events and eventually we are back at our EvilFoo (non- local).
So, re-entrance is the root problem, not the recursive lock. Now, if you felt more on the safe side using a non-recursive lock, how would such a bug manifest itself? In a deadlock whenever unexpected re-entrance occurs. And with a recursive lock? The same way, it would manifest itself in code without any locks.
So the evil part of EvilFoo
are the events and how they are implemented, not so much a recursive lock. fireChangedEvent()
would need to first create a copy of changedEventHandlers
and use that for iteration, for starters.
Another aspect often coming into the discussion is the definition of what a lock is supposed to do in the first place:
The way I do my concurrent programming, I have a mental model of the latter (protect a resource). This is the main reason why I am good with recursive locks. If some (member) function needs locking of a resource, it locks. If it calls another (member) function while doing what it does and that function also needs locking - it locks. And I don't need an "alternate approach", because the ref-counting of the recursive lock is quite the same as if each function wrote something like:
void EvilFoo::bar() {
auto_lock lock(this); // this->lock_holder = this->lock_if_not_already_locked_by_same_thread())
// do what we gotta do
// ~auto_lock() { if (lock_holder) unlock() }
}
And once events or similar constructs (visitors?!) come into play, I do not hope to get all the ensuing design problems solved by some non-recursive lock.
Have you tried 'GapDebug'? Its free.
It appears to integrate versions of the Safari Webkit Inspector and Chrome Dev Tools to offer an integrated debugging experience on OS X and Windows.
Using ES6 syntax, if you need a "pipeline" like process where you pass the same object through a series of functions (in my case, a HTML abstract syntax tree), you can use for...of
to call each pipe function in a given array:
const setMainElement = require("./set-main-element.js")
const cacheImages = require("./cache-images.js")
const removeElements = require("./remove-elements.js")
let htmlAst = {}
const pipeline = [
setMainElement,
cacheImages,
removeElements,
(htmlAst) => {
// Using a dynamic closure.
},
]
for (const pipe of pipeline) {
pipe(htmlAst)
}
You may have as many levels of Object hierarchy as you want, as long you declare an Object as being a property of another parent Object. Pay attention to the commas on each level, that's the tricky part. Don't use commas after the last element on each level:
{el1, el2, {el31, el32, el33}, {el41, el42}}
var MainObj = {_x000D_
_x000D_
prop1: "prop1MainObj",_x000D_
_x000D_
Obj1: {_x000D_
prop1: "prop1Obj1",_x000D_
prop2: "prop2Obj1", _x000D_
Obj2: {_x000D_
prop1: "hey you",_x000D_
prop2: "prop2Obj2"_x000D_
}_x000D_
},_x000D_
_x000D_
Obj3: {_x000D_
prop1: "prop1Obj3",_x000D_
prop2: "prop2Obj3"_x000D_
},_x000D_
_x000D_
Obj4: {_x000D_
prop1: true,_x000D_
prop2: 3_x000D_
} _x000D_
};_x000D_
_x000D_
console.log(MainObj.Obj1.Obj2.prop1);
_x000D_
The following example shows benchmarks for a few alternatives.
library(rbenchmark) # Note spelling: "rbenchmark", not "benchmark"
benchmark(seq(0,1e6,by=2),(0:5e5)*2,seq.int(0L,1e6L,by=2L))
## test replications elapsed relative user.self sys.self
## 2 (0:5e+05) * 2 100 0.587 3.536145 0.344 0.244
## 1 seq(0, 1e6, by = 2) 100 2.760 16.626506 1.832 0.900
## 3 seq.int(0, 1e6, by = 2) 100 0.166 1.000000 0.056 0.096
In this case, seq.int
is the fastest method and seq
the slowest. If performance of this step isn't that important (it still takes < 3 seconds to generate a sequence of 500,000 values), I might still use seq
as the most readable solution.
As an alternative to rendering a raster image, you can embed a SVG:
https://gist.github.com/CyberShadow/95621a949b07db295000
Unfortunately, even though you can select and copy text when you open the .svg file, the text is not selectable when the SVG image is embedded.
Note: There is no magic to animating a gif: it is either an animated gif or it is not. If the gif is not visible, very likely the path to the gif is wrong - or, as in your case, the container (div/p/etc) is not large enough to display it. In your code sample, you did not specify height or width and that appeared to be problem.
If the gif is displayed but not animating, see reference links at very bottom of this answer.
Displaying the gif + overlay, however, is easier than you might think.
All you need are two absolute-position DIVs: an overlay div, and a div that contains your loading gif. Both have higher z-index than your page content, and the image has a higher z-index than the overlay - so they will display above the page when visible.
So, when the button is pressed, just unhide those two divs. That's it!
$("#button").click(function() {_x000D_
$('#myOverlay').show();_x000D_
$('#loadingGIF').show();_x000D_
setTimeout(function(){_x000D_
$('#myOverlay, #loadingGIF').fadeOut();_x000D_
},2500);_x000D_
});_x000D_
/* Or, remove overlay/image on click background... */_x000D_
$('#myOverlay').click(function(){_x000D_
$('#myOverlay, #loadingGIF').fadeOut();_x000D_
});
_x000D_
body{font-family:Calibri, Helvetica, sans-serif;}_x000D_
#myOverlay{position:absolute;top:0;left:0;height:100%;width:100%;}_x000D_
#myOverlay{display:none;backdrop-filter:blur(4px);background:black;opacity:.4;z-index:2;}_x000D_
_x000D_
#loadingGIF{position:absolute;top:10%;left:35%;z-index:3;display:none;}_x000D_
_x000D_
button{margin:5px 30px;padding:10px 20px;}
_x000D_
<div id="myOverlay"></div>_x000D_
<div id="loadingGIF"><img src="http://placekitten.com/150/80" /></div>_x000D_
_x000D_
<div id="abunchoftext">_x000D_
Once upon a midnight dreary, while I pondered weak and weary, over many a quaint and curious routine of forgotten code... While I nodded, nearly napping, suddenly there came a tapping... as of someone gently rapping - rapping at my office door. 'Tis the team leader, I muttered, tapping at my office door - only this and nothing more. Ah, distinctly I remember it was in the bleak December and each separate React print-out lay there crumpled on the floor. Eagerly I wished the morrow; vainly I had sought to borrow from Stack-O surcease from sorrow - sorrow for my routine's core. For the brilliant but unworking code my angels seem to just ignore. I'll be tweaking code... forevermore! - <a href="http://www.online-literature.com/poe/335/" target="_blank">Apologies To Poe</a></div>_x000D_
<button id="button">Submit</button>_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
_x000D_
You might enjoy playing with the new backdrop-filter:blur(_px)
css property that gives a blur effect to the underlying content, as used in above demo... (As of April 2020: works in Chrome, Edge, Safari, Android, but not yet in Firefox)
References:
http://www.paulirish.com/2007/animated-gif-not-animating/
Animated GIF while loading page does not animate
https://wordpress.org/support/topic/animated-gif-not-working
use
console.log(variable)
and if you using google chrome open Console by using Ctrl+Shift+j
Goto >> Console
To select properties a
AND b
of a X
element:
X[a][b]
To select properties a
OR b
of a X
element:
X[a],X[b]
I solve this problem with this code in NugetPackageConsole.and it works.The problem was in the version. i thikn it will help others.
Douglas Crockford discusses that topic extensively in The Good Parts. He recommends to avoid the new operator to create new objects. Instead he proposes to create customized constructors. For instance:
var mammal = function (spec) {
var that = {};
that.get_name = function ( ) {
return spec.name;
};
that.says = function ( ) {
return spec.saying || '';
};
return that;
};
var myMammal = mammal({name: 'Herb'});
In Javascript a function is an object, and can be used to construct objects out of together with the new operator. By convention, functions intended to be used as constructors start with a capital letter. You often see things like:
function Person() {
this.name = "John";
return this;
}
var person = new Person();
alert("name: " + person.name);**
In case you forget to use the new operator while instantiating a new object, what you get is an ordinary function call, and this is bound to the global object instead to the new object.
If you are thinking of running a server and trying to decide how many connections can be served from one machine, you may want to read about the C10k problem and the potential problems involved in serving lots of clients simultaneously.
You need to define the size of file...
header('Content-Length: ' . filesize($file));
And this line is wrong:
header("Content-Disposition:inline;filename='$filename");
You messed up quotas.
I recommend you start reading the documentation (4.6.18. Formatting cells). When applying a lot of formatting it's better to use applyFromArray()
According to the documentation this method is also suppose to be faster when you're setting many style properties. There's an annex where you can find all the possible keys for this function.
This will work for you:
$phpExcel = new PHPExcel();
$styleArray = array(
'font' => array(
'bold' => true,
'color' => array('rgb' => 'FF0000'),
'size' => 15,
'name' => 'Verdana'
));
$phpExcel->getActiveSheet()->getCell('A1')->setValue('Some text');
$phpExcel->getActiveSheet()->getStyle('A1')->applyFromArray($styleArray);
To apply font style to complete excel document:
$styleArray = array(
'font' => array(
'bold' => true,
'color' => array('rgb' => 'FF0000'),
'size' => 15,
'name' => 'Verdana'
));
$phpExcel->getDefaultStyle()
->applyFromArray($styleArray);
I think it is confusing to think of it in terms of negative numbers. Since it is a logarithm think of the negative values the same way you think of powers of ten. 10^3 = 1000 while 10^-3 = 0.001.
With this in mind and using the formulas from S Lists's answer (and assuming our base power is 1mW in all these cases) we can build a little table:
|--------|-------------------|
| P(dBm) | P(mW) |
|--------|-------------------|
| 50 | 100000 |
| 40 | 10000 | strong transmitter
| 30 | 1000 | ^
| 20 | 100 | |
| 10 | 10 | |
| 0 | 1 |
| -10 | 0.1 |
| -20 | 0.01 |
| -30 | 0.001 |
| -40 | 0.0001 |
| -50 | 0.00001 | |
| -60 | 0.000001 | |
| -70 | 0.0000001 | v
| -80 | 0.00000001 | sensitive receiver
| -90 | 0.000000001 |
|--------|-------------------|
When I think of it like this I find that it's easier to see that the more negative the dBm value then the farther to the right of the decimal the actual power value is.
When it comes to mobile networks, it not so much that they aren't powerful enough, rather it is that they are more sensitive. When you see receivers specs with dBm far into the negative values, then what you are seeing is more sensitive equipment.
Normally you would want your transmitter to be powerful (further in to the positives) and your receiver to be sensitive (further in to the negatives).
Try :
List<string> MyList = new List<string>();
MyList.Add("HELLO");
MyList.Add("WORLD");
listBox1.DataSource = MyList;
Have a look at ListControl.DataSource Property
The %pdb
magic command is good to use as well. Just say %pdb on
and subsequently the pdb
debugger will run on all exceptions, no matter how deep in the call stack. Very handy.
If you have a particular line that you want to debug, just raise an exception there (often you already are!) or use the %debug
magic command that other folks have been suggesting.
From the documentation of XPath ( http://www.w3.org/TR/xpath/#location-paths ):
child::*
selects all element children of the context node
child::text()
selects all text node children of the context node
child::node()
selects all the children of the context node, whatever their node type
So I guess your answer is:
$doc/PRESENTEDIN/X/child::node()
And if you want a flatten array of all nested nodes:
$doc/PRESENTEDIN/X/descendant::node()
I had this problem and it turned out the issue was that I had named my repository with CamelCase. Bitbucket automatically changes the URL of your repository to be all lower case and that gets sent to Jenkins in the webhook. Jenkins then searches for projects with a matching repository. If you, like me, have CamelCase in your repository URL in your project configuration you will be able to check out code, but the pattern matching on the webhook request will fail.
Just change your repo URL to be all lower case instead of CamelCase and the pattern match should find your project.
Well, using the HTML validator at w3.org, specific to HTML5, IDs must be unique
Consider the following...
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>MyTitle</title>
</head>
<body>
<div id="x">Barry</div>
<div id="x">was</div>
<div id="x">here</div>
</body>
</html>
the validator responds with ...
Line 9, Column 14: Duplicate ID x. <div id="x">was</div>
Warning Line 8, Column 14: The first occurrence of ID x was here. <div id="x">Barry</div>
Error Line 10, Column 14: Duplicate ID x. <div id="x">here</div>
Warning Line 8, Column 14: The first occurrence of ID x was here. <div id="x">Barry</div>
... but the OP specifically stated - what about different element types. So consider the following HTML...
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>MyTitle</title>
</head>
<body>
<div id="x">barry
<span id="x">was here</span>
</div>
</body>
</html>
... the result from the validator is...
Line 9, Column 16: Duplicate ID x. <span id="x">was here</span>
Warning Line 8, Column 14: The first occurrence of ID x was here. <div id="x">barry
In either case (same element type, or different element type), if the id is used more than once it is not considered valid HTML5.
Just use the build-in feature of Angular CLI
ng update
to update to the latest version.
A simple method will be like this:
Match match1 = Regex.Match(<input_string>, @"(?=.{7})");
match1.Success ensures that there are at least 8 characters.
Match match2 = Regex.Match(<input_string>, [^a-zA-Z]);
match2.Success ensures that there is at least one special character or number within the string.
So, match1.Success && match2.Success guarantees will get what you want.
i am using this two method steps for preserve same text which is in textarea to store in mysql and at a getting time i can also simply displaying plain text.....
step 1:
$status=$_POST['status'];<br/>
$textToStore = nl2br(htmlentities($status, ENT_QUOTES, 'UTF-8'));
In query enter $textToStore
....
step 2:
write code for select query...and direct echo values....
It works
You can pass it in as part of the LinearLayout.LayoutParams
constructor:
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT,
1.0f
);
YOUR_VIEW.setLayoutParams(param);
The last parameter is the weight.
void foo(void)
is better because it explicitly says: no parameters allowed.
void foo()
means you could (under some compilers) send parameters, at least if this is the declaration of your function rather than its definition.
LG, VIZIO, SAMSUNG and PANASONIC TVs are not android based, and you cannot run APKs off of them... You should just buy a fire stick and call it a day. The only TVs that are android-based, and you can install APKs are: SONY, PHILIPS and SHARP.
#FACTS.
If we see the Definition of Object and Instance object -
Memory allocated for the member of class at run time is called object or object is the instance of Class.
Let us see the Definition of instance -
Memory allocated For Any at run time is called as instance variable.
Now understand the meaning of any run time memory allocation happen in C also through Malloc, Calloc, Realloc such:
struct p
{
}
p *t1
t1=(p) malloc(sizeof(p))
So here also we are allocating run time memory allocation but here we call as instance so t1 is instance here we can not say t1 as object so Every object is the instance of Class but every Instance is not Object.
Most modern devices support the tel: scheme. So use <a href="tel:555-555-5555">555-555-5555</a>
and you should be good to go.
If you want to use it for an image, the <a>
tag can handle the <img/>
placed in it just like other normal situations with : <a href="tel:555-555-5555"><img src="path/to/phone/icon.jpg" /></a>
Only using css techniques this does not seem possible to me. But you could use jqueryui draggable:
$('#drag_me').draggable();
I was experiencing this issue on a drupal site and none of the other solutions in this thread helped. After some troubleshooting I found the local.settings.php had a closing tag with a space after it like so:
<?php
$databases = array(
'default' =>
array (
'default' =>
array (
'driver' => 'mysql',
'database' => 'xxx',
'username' => 'xxx',
'password' => 'xxx',
'port' => '',
'host' => 'xxx',
),
),
);
?>
Updating local.settings.php to the following resolved:
<?php
$databases = array(
'default' =>
array (
'default' =>
array (
'driver' => 'mysql',
'database' => 'xxx',
'username' => 'xxx',
'password' => 'xxx',
'port' => '',
'host' => 'xxx',
),
),
);
The closing "?>" PHP tag is not necessary here. If you choose to use a closing tag you must ensure there are no characters / whitespace after it.
PreparedStatements are the way to go, because they make SQL injection impossible. Here's a simple example taking the user's input as the parameters:
public insertUser(String name, String email) {
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = setupTheDatabaseConnectionSomehow();
stmt = conn.prepareStatement("INSERT INTO person (name, email) values (?, ?)");
stmt.setString(1, name);
stmt.setString(2, email);
stmt.executeUpdate();
}
finally {
try {
if (stmt != null) { stmt.close(); }
}
catch (Exception e) {
// log this error
}
try {
if (conn != null) { conn.close(); }
}
catch (Exception e) {
// log this error
}
}
}
No matter what characters are in name and email, those characters will be placed directly in the database. They won't affect the INSERT statement in any way.
There are different set methods for different data types -- which one you use depends on what your database fields are. For example, if you have an INTEGER column in the database, you should use a setInt
method. The PreparedStatement documentation lists all the different methods available for setting and getting data.
They behave the same but toString
also provides a way to convert a number binary, octal, or hexadecimal strings:
Example:
var a = (50274).toString(16) // "c462"
var b = (76).toString(8) // "114"
var c = (7623).toString(36) // "5vr"
var d = (100).toString(2) // "1100100"
I don't think you can design the if-then-else construct without taking the design for other constructs into account. I think it's a good principle that each expression should be an element, and its subexpressions should be child elements. There are then questions about whether the name of an element should reflect the type of expression it is, or its role relative to the parent. Or you can do both:
<if>
<condition>
<equals>
<number>2</number>
<number>3</number>
<equals>
<condition>
<then>
<string>Mary</string>
</then>
<else>
<concat>
<string>John</string>
<string>Smith</string>
</concat>
</else>
</if>
But you can sometimes get away with a design that omits the role-names (condition, then else) and relies on positional significance of elements relative to their parent. It depends a bit on how much you want to keep it concise.
on Centos 7, this will do it, for Tomcat 7 : (my tomcat install dir: opt/apache-tomcat-7.0.79)
not sure the log link is necessary, the configuration is the critical one.
:
Yes for some reason WebView.reload() causes a crash if it failed to load before (something to do with the way it handles history). This is the code I use to refresh my webview. I store the current url in self.url
# 1: Pause timeout and page loading
self.timeout.pause()
sleep(1)
# 2: Check for internet connection (Really lazy way)
while self.page().networkAccessManager().networkAccessible() == QNetworkAccessManager.NotAccessible: sleep(2)
# 3:Try again
if self.url == self.page().mainFrame().url():
self.page().action(QWebPage.Reload)
self.timeout.resume(60)
else:
self.page().action(QWebPage.Stop)
self.page().mainFrame().load(self.url)
self.timeout.resume(30)
return False
Use sprintf()
:
int someInt = 368;
char str[12];
sprintf(str, "%d", someInt);
All numbers that are representable by int
will fit in a 12-char-array without overflow, unless your compiler is somehow using more than 32-bits for int
. When using numbers with greater bitsize, e.g. long
with most 64-bit compilers, you need to increase the array size—at least 21 characters for 64-bit types.
Just in case you don't want to import a big library like jQuery to accomplish something this trivial, you can use the built-in method querySelectorAll
instead. Almost all selector strings used for jQuery work with DOM methods as well:
const anchors = document.querySelectorAll('a[href$="ABC"]');
Or, if you know that there's only one matching element:
const anchor = document.querySelector('a[href$="ABC"]');
You may generally omit the quotes around the attribute value if the value you're searching for is alphanumeric, eg, here, you could also use
a[href$=ABC]
but quotes are more flexible and generally more reliable.
Is there a way to create a list of primitive int or any primitives in java
No you can't. You can only create List of reference types, like Integer
, String
, or your custom type.
It seems I can do
List myList = new ArrayList();
and add "int" into this list.
When you add int
to this list, it is automatically boxed to Integer
wrapper type. But it is a bad idea to use raw type lists, or for any generic type for that matter, in newer code.
I can add anything into this list.
Of course, that is the dis-advantage of using raw type. You can have Cat, Dog, Tiger, Dinosaur, all in one container.
Is my only option, creating an array of int and converting it into a list
In that case also, you will get a List<Integer>
only. There is no way you can create List<int>
or any primitives.
You shouldn't be bothered anyways. Even in List<Integer>
you can add an int
primitive types. It will be automatically boxed, as in below example:
List<Integer> list = new ArrayList<Integer>();
list.add(5);
The WSDL is a kind of contract between API provider and the client it's describe the web service : the public function , optional/required field ...
But The soap message is a data transferred between client and provider (payload)
or just use $.trim(str)
- Where does
user.id
go afterpassport.serializeUser
has been called?
The user id (you provide as the second argument of the done
function) is saved in the session and is later used to retrieve the whole object via the deserializeUser
function.
serializeUser
determines which data of the user object should be stored in the session. The result of the serializeUser method is attached to the session as req.session.passport.user = {}
. Here for instance, it would be (as we provide the user id as the key) req.session.passport.user = {id: 'xyz'}
- We are calling
passport.deserializeUser
right after it where does it fit in the workflow?
The first argument of deserializeUser
corresponds to the key of the user object that was given to the done
function (see 1.). So your whole object is retrieved with help of that key. That key here is the user id (key can be any key of the user object i.e. name,email etc).
In deserializeUser
that key is matched with the in memory array / database or any data resource.
The fetched object is attached to the request object as req.user
Visual Flow
passport.serializeUser(function(user, done) {
done(null, user.id);
}); ¦
¦
¦
+--------------------? saved to session
¦ req.session.passport.user = {id: '..'}
¦
?
passport.deserializeUser(function(id, done) {
+---------------+
¦
?
User.findById(id, function(err, user) {
done(err, user);
}); +--------------? user object attaches to the request as req.user
});
One method that uses less math/theory is to sample 2, 5, 7, or 10 data points at a time and determine those which are outliers. A less accurate measure of an outlier than a Kalman Filter is to to use the following algorithm to take all pair wise distances between points and throw out the one that is furthest from the the others. Typically those values are replaced with the value closest to the outlying value you are replacing
For example
Smoothing at five sample points A, B, C, D, E
ATOTAL = SUM of distances AB AC AD AE
BTOTAL = SUM of distances AB BC BD BE
CTOTAL = SUM of distances AC BC CD CE
DTOTAL = SUM of distances DA DB DC DE
ETOTAL = SUM of distances EA EB EC DE
If BTOTAL is largest you would replace point B with D if BD = min { AB, BC, BD, BE }
This smoothing determines outliers and can be augmented by using the midpoint of BD instead of point D to smooth the positional line. Your mileage may vary and more mathematically rigorous solutions exist.
You cannot play a video inside a view. It has to be played fullscreen.
If you are using 12.2, you can simply say
set markup csv on
spool myfile.csv
Yes, that is correct.
Not putting an expires
part in will create a session cookie, whether it is created in JavaScript or on the server.
You can use either of below :-
1) display : inline-block :
http://jsbin.com/feneni/edit?html,css,js,output
Uncomment the line
float:left;
clear:both
and you will find that parent container has collapsed.
2) Using display : table
I was having the same issue and the reason for it was because I was trying to load a UIImage with the wrong name. Double-check .setImage(UIImage(named: "-name-"
calls and make sure the name is correct.
For just reading the last element of a slice:
sl[len(sl)-1]
For removing it:
sl = sl[:len(sl)-1]
See this page about slice tricks
I was stumped by this. Once I got passed the 255 problem... I ended up with a mysterious error code 1. This is the foo to get that resolved:
pssh -x '-tt' -h HOSTFILELIST -P "sudo yum -y install glibc"
-P means write the output out as you go and is optional. But the -x '-tt' trick is what forces a psuedo tty to be allocated.
You can get a clue what the error code 1 means this if you try:
ssh AHOST "sudo yum -y install glibc"
You may see:
[slc@bastion-ci ~]$ ssh MYHOST "sudo yum -y install glibc"
sudo: sorry, you must have a tty to run sudo
[slc@bastion-ci ~]$ echo $?
1
Notice the return code for this is 1, which is what pssh is reporting to you.
I found this -x -tt trick here. Also note that turning on verbose mode (pssh --verbose) for these cases does nothing to help you.
The %s
specifier converts the object using str()
, and %r
converts it using repr()
.
For some objects such as integers, they yield the same result, but repr()
is special in that (for types where this is possible) it conventionally returns a result that is valid Python syntax, which could be used to unambiguously recreate the object it represents.
Here's an example, using a date:
>>> import datetime
>>> d = datetime.date.today()
>>> str(d)
'2011-05-14'
>>> repr(d)
'datetime.date(2011, 5, 14)'
Types for which repr()
doesn't produce Python syntax include those that point to external resources such as a file
, which you can't guarantee to recreate in a different context.
$object = new stdClass();
$object->id = 1;
$object2 = new stdClass();
$object2->id = 2;
$objects = [
$object,
$object2
];
$ids = array_map(function ($object) {
/** @var YourEntity $object */
return $object->id;
// Or even if you have public methods
// return $object->getId()
}, $objects);
Output: [1, 2]
Here is a combination of the answer by @Mohsenasm and a comment from @Ghigo adopted to Swift
extension UIView {
var globalFrame: CGRect? {
let rootView = UIApplication.shared.keyWindow?.rootViewController?.view
return self.superview?.convert(self.frame, to: rootView)
}
}
To post JSON, you will need to stringify it. JSON.stringify
and set the processData
option to false.
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
processData: false,
contentType: "application/json; charset=UTF-8",
complete: callback
});
my best solution to get the first is
df['my_column'].value_counts().sort_values(ascending=False).argmax()
If your main element has some child elements or text, you could make use of it.
Position your main element relative (or absolute/fixed) and use both :before and :after positioned absolute (in my situation it had to be absolute, don't know about your's).
Now if you want one more pseudo-element, attach an absolute :before to one of the main element's children (if you have only text, put it in a span, now you have an element), which is not relative/absolute/fixed.
This element will start acting like his owner is your main element.
HTML
<div class="circle">
<span>Some text</span>
</div>
CSS
.circle {
position: relative; /* or absolute/fixed */
}
.circle:before {
position: absolute;
content: "";
/* more styles: width, height, etc */
}
.circle:after {
position: absolute;
content: "";
/* more styles: width, height, etc */
}
.circle span {
/* not relative/absolute/fixed */
}
.circle span:before {
position: absolute;
content: "";
/* more styles: width, height, etc */
}
There really isn't any way of doing this as most of the useful information is discarded in the compilation process. However, you may want to take a look at this site to see if you can find some way of extracting something from the DLL.
Data Flow Diagrams The formal, structured analysis approach employs the data-flow diagram (DFD) to assist in the functional decomposition process. I learned structured analysis techniques from DeMarco [7], and those techniques are representative of present conventions. To summarize, DFD's are comprised of four components:
This is all awkward and not local settings independent. Do it like this:
%CYGWIN_DIR%\bin\date +%%Y%%m%%d_%%H%%M% > date.txt
for /f "delims=" %%a in ('type "date.txt" 2^>NUL') do set datetime=%%a
echo %datetime%
del date.txt
Yes, use Cygwin date and all your problems are gone!
You need a whole input match here.
System.out.println(test.matches("^(http|https|ftp)://.*$"));
Edit:(Based on @davidchambers's comment)
System.out.println(test.matches("^(https?|ftp)://.*$"));
A couple of issues
>
in -exec
without something like bash -c '... > ...'
. Though the >
will overwrite the file, so you want to redirect the entire find
anyway rather than each -exec
. +30
is older
than 30 days, -30
would be modified in last 30 days.-exec
really isn't needed, you could list everything with various -printf
options. Something like below should work
find . -type f -mtime -30 -exec ls -l {} \; > last30days.txt
Example with -printf
find . -type f -mtime -30 -printf "%M %u %g %TR %TD %p\n" > last30days.txt
This will list files in format "permissions owner group time date filename". -printf
is generally preferable to -exec
in cases where you don't have to do anything complicated. This is because it will run faster as a result of not having to execute subshells for each -exec
. Depending on the version of find
, you may also be able to use -ls
, which has a similar format to above.
In postman - Have you tried adding the header element 'Accept' as 'application/vnd.ms-excel'
setting the overflow
should take care of it, but you need to set the height of Content
also. If the height attribute is not set, the div will grow vertically as tall as it needs to, and scrollbars wont be needed.
See Example: http://jsfiddle.net/ftkbL/1/
It might be that the package "Combinations" is not updated anymore and does not work with a recent version of R (I was also unable to install it on R 2.13.1 on windows). The package "combinat" installs without problem for me and might be a solution for you depending on what exactly you're trying to do.
Although several other users have posted adequate solutions, I'd like to post a more general approach that may be more useful.
This is largely based on JYelton's response.
public static IEnumerable<Control> AllControls(
this Control control,
Func<Control, Boolean> filter = null)
{
if (control == null)
throw new ArgumentNullException("control");
if (filter == null)
filter = (c => true);
var list = new List<Control>();
foreach (Control c in control.Controls) {
list.AddRange(AllControls(c, filter));
if (filter(c))
list.Add(c);
}
return list;
}
Split creates an array . You can access the individual values by using a index.
var result=$(row).val().split('|')[2]
alert(result);
OR
var result=$(row).val().split('|');
alert(result[2]);
If it's input element then you need to use $(row).val()
to get the value..
Otherwise you would need to use $(row).text()
or $(row).html()
Use count()
:
sc=scorm.objects.filter(Header__id=qp.id)
if sc.count() > 0:
...
The advantage over e.g. len()
is, that the QuerySet is not yet evaluated:
count()
performs aSELECT COUNT(*)
behind the scenes, so you should always usecount()
rather than loading all of the record into Python objects and callinglen()
on the result.
Having this in mind, When QuerySets are evaluated can be worth reading.
If you use get()
, e.g. scorm.objects.get(pk=someid)
, and the object does not exists, an ObjectDoesNotExist
exception is raised:
from django.core.exceptions import ObjectDoesNotExist
try:
sc = scorm.objects.get(pk=someid)
except ObjectDoesNotExist:
print ...
Update:
it's also possible to use exists()
:
if scorm.objects.filter(Header__id=qp.id).exists():
....
Returns
True
if the QuerySet contains any results, andFalse
if not. This tries to perform the query in the simplest and fastest way possible, but it does execute nearly the same query as a normal QuerySet query.
Best approach:
public static boolean isOnline() {
try {
InetAddress.getByName("google.com").isReachable(3);
return true;
} catch (UnknownHostException e){
return false;
} catch (IOException e){
return false;
}
}
Another way is
> length(z[z==TRUE])
[1] 498
While sum(z)
is nice and short, for me length(z[z==TRUE])
is more self explaining. Though, I think with a simple task like this it does not really make a difference...
If it is a large vector, you probably should go with the fastest solution, which is sum(z)
. length(z[z==TRUE])
is about 10x slower and table(z)[TRUE]
is about 200x slower than sum(z)
.
Summing up, sum(z)
is the fastest to type and to execute.
hadoop.tmp.dir
in the core-site.xml is defaulted to /tmp/hadoop-${user.name}
which is cleaned after every reboot. Change this to some other directory which doesn't get cleaned on reboot.
I was facing above error when i am trying to plot histogram and below points worked for me.
OS : Mac Catalina 10.15.5
Pycharm Version : Community version 2019.2.3
Python version : 3.7
from :
import matplotlib.pylab as plt
to:
import matplotlib.pyplot as plt
from:
plt.pyplot.hist(df["horsepower"])
# set x/y labels and plot title
plt.pyplot.xlabel("horsepower")
plt.pyplot.ylabel("count")
plt.pyplot.title("horsepower bins")
to :
plt.hist(df["horsepower"])
# set x/y labels and plot title
plt.xlabel("horsepower")
plt.ylabel("count")
plt.title("horsepower bins")
plt.show()
__pycache__
is a folder containing Python 3 bytecode compiled and ready to be executed.
I don't recommend routinely deleting these files or suppressing creation during development as it may hurt performance. Just have a recursive command ready (see below) to clean up when needed as bytecode can become stale in edge cases (see comments).
Python programmers usually ignore bytecode. Indeed __pycache__
and *.pyc
are common lines to see in .gitignore
files. Bytecode is not meant for distribution and can be disassembled using dis
module.
If you are using OS X you can easily hide all of these folders in your project by running following command from the root folder of your project.
find . -name '__pycache__' -exec chflags hidden {} \;
Replace __pycache__
with *.pyc
for Python 2.
This sets a flag on all those directories (.pyc files) telling Finder/Textmate 2 to exclude them from listings. Importantly the bytecode is there, it's just hidden.
Rerun the command if you create new modules and wish to hide new bytecode or if you delete the hidden bytecode files.
On Windows the equivalent command might be (not tested, batch script welcome):
dir * /s/b | findstr __pycache__ | attrib +h +s +r
Which is same as going through the project hiding folders using right-click > hide...
Running unit tests is one scenario (more in comments) where deleting the *.pyc
files and __pycache__
folders is indeed useful. I use the following lines in my ~/.bash_profile
and just run cl
to clean up when needed.
alias cpy='find . -name "__pycache__" -delete'
alias cpc='find . -name "*.pyc" -delete'
...
alias cl='cpy && cpc && ...'
and more lately
# pip install pyclean
pyclean .
If you have cells with something like =""
and don't want to count them, you have to subtract number of empty cells from total number of cell by formula like
=row(G101)-row(G4)+1-countblank(G4:G101)
In case of 2-dimensional array it would be
=(row(G101)-row(A4)+1)*(column(G101)-column(A4)+1)-countblank(A4:G101)
Tested at google docs.
It's usually to namespace (see later) and control the visibility of member functions and/or variables. Think of it like an object definition. The technical name for it is an Immediately Invoked Function Expression (IIFE). jQuery plugins are usually written like this.
In Javascript, you can nest functions. So, the following is legal:
function outerFunction() {
function innerFunction() {
// code
}
}
Now you can call outerFunction()
, but the visiblity of innerFunction()
is limited to the scope of outerFunction()
, meaning it is private to outerFunction()
. It basically follows the same principle as variables in Javascript:
var globalVariable;
function someFunction() {
var localVariable;
}
Correspondingly:
function globalFunction() {
var localFunction1 = function() {
//I'm anonymous! But localFunction1 is a reference to me!
};
function localFunction2() {
//I'm named!
}
}
In the above scenario, you can call globalFunction()
from anywhere, but you cannot call localFunction1
or localFunction2
.
What you're doing when you write (function() { ... })()
, is you're making the code inside the first set of parentheses a function literal (meaning the whole "object" is actually a function). After that, you're self-invoking the function (the final ()
) that you just defined. So the major advantage of this as I mentioned before, is that you can have private methods/functions and properties:
(function() {
var private_var;
function private_function() {
//code
}
})();
In the first example, you would explicitly invoke globalFunction
by name to run it. That is, you would just do globalFunction()
to run it. But in the above example, you're not just defining a function; you're defining and invoking it in one go. This means that when the your JavaScript file is loaded, it is immediately executed. Of course, you could do:
function globalFunction() {
// code
}
globalFunction();
The behavior would largely be the same except for one significant difference: you avoid polluting the global scope when you use an IIFE (as a consequence it also means that you cannot invoke the function multiple times since it doesn't have a name, but since this function is only meant to be executed once it really isn't an issue).
The neat thing with IIFEs is that you can also define things inside and only expose the parts that you want to the outside world so (an example of namespacing so you can basically create your own library/plugin):
var myPlugin = (function() {
var private_var;
function private_function() {
}
return {
public_function1: function() {
},
public_function2: function() {
}
}
})()
Now you can call myPlugin.public_function1()
, but you cannot access private_function()
! So pretty similar to a class definition. To understand this better, I recommend the following links for some further reading:
EDIT
I forgot to mention. In that final ()
, you can pass anything you want inside. For example, when you create jQuery plugins, you pass in jQuery
or $
like so:
(function(jQ) { ... code ... })(jQuery)
So what you're doing here is defining a function that takes in one parameter (called jQ
, a local variable, and known only to that function). Then you're self-invoking the function and passing in a parameter (also called jQuery
, but this one is from the outside world and a reference to the actual jQuery itself). There is no pressing need to do this, but there are some advantages:
Earlier I described how these functions run automatically at startup, but if they run automatically who is passing in the arguments? This technique assumes that all the parameters you need are already defined as global variables. So if jQuery wasn't already defined as a global variable this example would not work. As you might guess, one things jquery.js does during its initialization is define a 'jQuery' global variable, as well as its more famous '$' global variable, which allows this code to work after jQuery has been included.
git push -f heroku local_branch_name:master
Write this in your View Controller class of your Tab Bar:
// Generate a black tab bar
self.tabBarController.tabBar.barTintColor = [UIColor blackColor];
// Set the selected icons and text tint color
self.tabBarController.tabBar.tintColor = [UIColor orangeColor];
If you want for some reason to convert your file to base-64 string. Like if you want to pass it via internet, etc... you can do this
Byte[] bytes = File.ReadAllBytes("path");
String file = Convert.ToBase64String(bytes);
And correspondingly, read back to file:
Byte[] bytes = Convert.FromBase64String(b64Str);
File.WriteAllBytes(path, bytes);
Read this:
http://www.quora.com/OAuth-2-0/How-does-OAuth-2-0-work
or an even simpler but quick explanation:
http://agileanswer.blogspot.se/2012/08/oauth-20-for-my-ninth-grader.html
The redirect URI is the callback entry point of the app. Think about how OAuth for Facebook works - after end user accepts permissions, "something" has to be called by Facebook to get back to the app, and that "something" is the redirect URI. Furthermore, the redirect URI should be different than the initial entry point of the app.
The other key point to this puzzle is that you could launch your app from a URL given to a webview. To do this, i simply followed the guide on here:
http://iosdevelopertips.com/cocoa/launching-your-own-application-via-a-custom-url-scheme.html
and
http://inchoo.net/mobile-development/iphone-development/launching-application-via-url-scheme/
note: on those last 2 links, "http://" works in opening mobile safari but "tel://" doesn't work in simulator
in the first app, I call
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"secondApp://"]];
In my second app, I register "secondApp" (and NOT "secondApp://") as the name of URL Scheme, with my company as the URL identifier.
For this sort of password, I tend to use a system that's likely to generate more easily "used" passwords. Short, often made up of pronouncable fragments and a few numbers, and with no intercharacter ambiguity (is that a 0 or an O? A 1 or an I?). Something like
string[] words = { 'bur', 'ler', 'meh', 'ree' };
string word = "";
Random rnd = new Random();
for (i = 0; i < 3; i++)
word += words[rnd.Next(words.length)]
int numbCount = rnd.Next(4);
for (i = 0; i < numbCount; i++)
word += (2 + rnd.Next(7)).ToString();
return word;
(Typed right into the browser, so use only as guidelines. Also, add more words).
Just use the ==
with the negation symbol (!
). If dtfm is the name of your data.frame:
dtfm[!dtfm$C == "Foo", ]
Or, to move the negation in the comparison:
dtfm[dtfm$C != "Foo", ]
Or, even shorter using subset()
:
subset(dtfm, C!="Foo")
I notice that your URL has spaces in it. I think that usually is a bad thing. Try encoding the URL with
$my_url = urlencode("my url");
and then calling
file_get_contents($my_url);
and see if you have better luck.
I'm not a JS pro, but I figured out a couple ways you could do this.
The HTML:
<p id="truncate">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi elementum consequat tortor et euismod. Nam commodo consequat libero vel lobortis. Morbi ac nisi at leo vehicula consectetur.</p>
Then with jQuery you truncate it down to a specific character count but leave the last word like this:
// Truncate but leave last word
var myTag = $('#truncate').text();
if (myTag.length > 100) {
var truncated = myTag.trim().substring(0, 100).split(" ").slice(0, -1).join(" ") + "…";
$('#truncate').text(truncated);
}
The result looks like this:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi
elementum consequat tortor et…
Or, you can simply truncate it down to a specific character count like this:
// Truncate to specific character
var myTag = $('#truncate').text();
if (myTag.length > 15) {
var truncated = myTag.trim().substring(0, 100) + "…";
$('#truncate').text(truncated);
}
The result looks like this:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi
elementum consequat tortor et euismod…
Hope that helps a bit.
Here is the jsFiddle.
...better is declare the name as varible ,and ask before if thereis a apostrophe in the string:
e.g.:
DIM YourName string
YourName = "Daniel O'Neal"
If InStr(YourName, "'") Then
SELECT * FROM tblStudents WHERE [name] Like """ Your Name """ ;
else
SELECT * FROM tblStudents WHERE [name] Like '" Your Name "' ;
endif
For my purposes I wanted all English ASCII chars, so this worked.
html = Regex.Replace(html, "[^\x00-\x80]+", "")
Using table-layout: fixed
as a property for table
and width: calc(100%/3);
for td
(assuming there are 3 td
's). With these two properties set, the table cells will be equal in size.
Refer to the demo.
I was facing the same issue, I resolved this by replacing dependencies in App level Build.gradle file
"""
implementation 'com.google.firebase:firebase-analytics:17.2.2'
implementation 'androidx.multidex:multidex:2.0.0'
testImplementation 'junit:junit:4.12'
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
androidTestImplementation 'com.androidx.support.test:runner:1.1.0'
androidTestImplementation 'com.androidx.support.test.espresso:espresso-core:3.1.0'
BY
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation platform('com.google.firebase:firebase-bom:26.1.1')
implementation 'com.google.firebase:firebase-analytics'
implementation 'androidx.multidex:multidex:2.0.1'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.androidx.support.test:runner:1.1.0'
androidTestImplementation 'com.androidx.support.test.espresso:espresso-core:3.1.0'
This resolves my issue.
If you are using large table and want to access of 10 percent of the data then run this following command: SELECT TOP 10 PERCENT * FROM Table1 ORDER BY NEWID();
Read about Storage Engines.
MyISAM:
The MyISAM storage engine in MySQL.
InnoDB:
The InnoDB storage engine in MySQL.
MyISAM Limitations:
InnoDB Limitations:
ROW_FORMAT=COMPRESSED
)For brief understanding read below links:
As an exploration of this topic, I have a presentation titled "Securing TodoMVC Using the Web Cryptography API" (video, code).
It uses the Web Cryptography API to store the todo list encrypted in localStorage by password protecting the application and using a password derived key for encryption. If you forget or lose the password, there is no recovery. (Disclaimer - it was a POC and not intended for production use.)
As the other answers state, this is still susceptible to XSS or malware installed on the client computer. However, any sensitive data would also be in memory when the data is stored on the server and the application is in use. I suggest that offline support may be the compelling use case.
In the end, encrypting localStorage probably only protects the data from attackers that have read only access to the system or its backups. It adds a small amount of defense in depth for OWASP Top 10 item A6-Sensitive Data Exposure, and allows you to answer "Is any of this data stored in clear text long term?" correctly.
First add the import line:
from pyspark.sql.functions import min, max
df.agg(min("age")).show()
+--------+
|min(age)|
+--------+
| 29|
+--------+
df.agg(max("age")).show()
+--------+
|max(age)|
+--------+
| 77|
+--------+
You may also use element.insertAdjacentHTML('beforeend', data);
Please read the "Security considerations" on MDN.
On Windows, the default location is: C:\ProgramData\Docker\containers\<container-id>-json.log
.
Well, Mr.ajb has resolved and pointed out the error in your code.
Coming to the second part of the code, that is, converting a string with letters to decimal integer below is code for that,
import java.util.Scanner;
public class HexaToDecimal
{
int number;
void getValue()
{
Scanner sc = new Scanner(System.in);
System.out.println("Please enter hexadecimal to convert: ");
number = Integer.parseInt(sc.nextLine(), 16);
sc.close();
}
void toConvert()
{
String decimal = Integer.toString(number);
System.out.println("The Decimal value is : " + decimal);
}
public static void main(String[] args)
{
HexaToDecimal htd = new HexaToDecimal();
htd.getValue();
htd.toConvert();
}
}
You can refer example on hexadecimal to decimal for more information.
For Python3
html = """\\u003Cdiv id=\\u0022contenedor\\u0022\\u003E \\u003Ch2 class=\\u0022text-left m-b-2\\u0022\\u003EInformaci\\u00f3n del veh\\u00edculo de patente AA345AA\\u003C\\/h2\\u003E\\n\\n\\n\\n \\u003Cdiv class=\\u0022panel panel-default panel-disabled m-b-2\\u0022\\u003E\\n \\u003Cdiv class=\\u0022panel-body\\u0022\\u003E\\n \\u003Ch2 class=\\u0022table_title m-b-2\\u0022\\u003EInformaci\\u00f3n del Registro Automotor\\u003C\\/h2\\u003E\\n \\u003Cdiv class=\\u0022col-md-6\\u0022\\u003E\\n \\u003Clabel class=\\u0022control-label\\u0022\\u003ERegistro Seccional\\u003C\\/label\\u003E\\n \\u003Cp\\u003ESAN MIGUEL N\\u00b0 1\\u003C\\/p\\u003E\\n \\u003Clabel class=\\u0022control-label\\u0022\\u003EDirecci\\u00f3n\\u003C\\/label\\u003E\\n \\u003Cp\\u003EMAESTRO ANGEL D\\u0027ELIA 766\\u003C\\/p\\u003E\\n \\u003Clabel class=\\u0022control-label\\u0022\\u003EPiso\\u003C\\/label\\u003E\\n \\u003Cp\\u003EPB\\u003C\\/p\\u003E\\n \\u003Clabel class=\\u0022control-label\\u0022\\u003EDepartamento\\u003C\\/label\\u003E\\n \\u003Cp\\u003E-\\u003C\\/p\\u003E\\n \\u003Clabel class=\\u0022control-label\\u0022\\u003EC\\u00f3digo postal\\u003C\\/label\\u003E\\n \\u003Cp\\u003E1663\\u003C\\/p\\u003E\\n \\u003C\\/div\\u003E\\n \\u003Cdiv class=\\u0022col-md-6\\u0022\\u003E\\n \\u003Clabel class=\\u0022control-label\\u0022\\u003ELocalidad\\u003C\\/label\\u003E\\n \\u003Cp\\u003ESAN MIGUEL\\u003C\\/p\\u003E\\n \\u003Clabel class=\\u0022control-label\\u0022\\u003EProvincia\\u003C\\/label\\u003E\\n \\u003Cp\\u003EBUENOS AIRES\\u003C\\/p\\u003E\\n \\u003Clabel class=\\u0022control-label\\u0022\\u003ETel\\u00e9fono\\u003C\\/label\\u003E\\n \\u003Cp\\u003E(11)46646647\\u003C\\/p\\u003E\\n \\u003Clabel class=\\u0022control-label\\u0022\\u003EHorario\\u003C\\/label\\u003E\\n \\u003Cp\\u003E08:30 a 12:30\\u003C\\/p\\u003E\\n \\u003C\\/div\\u003E\\n \\u003C\\/div\\u003E\\n\\u003C\\/div\\u003E \\n\\n\\u003Cp class=\\u0022text-center m-t-3 m-b-1 hidden-print\\u0022\\u003E\\n \\u003Ca href=\\u0022javascript:window.print();\\u0022 class=\\u0022btn btn-default\\u0022\\u003EImprim\\u00ed la consulta\\u003C\\/a\\u003E \\u0026nbsp; \\u0026nbsp;\\n \\u003Ca href=\\u0022\\u0022 class=\\u0022btn use-ajax btn-primary\\u0022\\u003EHacer otra consulta\\u003C\\/a\\u003E\\n\\u003C\\/p\\u003E\\n\\u003C\\/div\\u003E"""
print(html.replace("\\/", "/").encode().decode('unicode_escape'))
If you're working with a multiline string, like a code file:
<html>
<title>test</title>
<body>
<h1>test</h1>
</body>
</html>
And want to replace all leading lines, to get this result:
<html>
<title>test</title>
<body>
<h1>test</h1>
</body>
</html>
You must add the multiline
flag to your regex, ^
and $
match line by line:
string.replace(/^\s+|\s+$/gm, '');
Relevant quote from docs:
The "m" flag indicates that a multiline input string should be treated as multiple lines. For example, if "m" is used, "^" and "$" change from matching at only the start or end of the entire string to the start or end of any line within the string.
There is also this tool you can use. It supports multi-events .ics file creation. It also supports timezone as well.
To recap on the previous answers. If you have a list with [0,1,2]
and another one with [3,4,5]
and you want to merge them, so it becomes [0,1,2,3,4,5]
, you can either use chaining
or extending
and should know the differences to use it wisely for your needs.
Using the list
classes extend
method, you can do a copy of the elements from one list onto another. However this will cause extra memory usage, which should be fine in most cases, but might cause problems if you want to be memory efficient.
a = [0,1,2]
b = [3,4,5]
a.extend(b)
>>[0,1,2,3,4,5]
Contrary you can use itertools.chain
to wire many lists, which will return a so called iterator
that can be used to iterate over the lists. This is more memory efficient as it is not copying elements over but just pointing to the next list.
import itertools
a = [0,1,2]
b = [3,4,5]
c = itertools.chain(a, b)
Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. Used for treating consecutive sequences as a single sequence.
According to the Android Development Guide:
px = dp * (dpi / 160)
But often you'll want do perform this the other way around when you receive a design that's stated in pixels. So:
dp = px / (dpi / 160)
If you're on a 240dpi device this ratio is 1.5 (like stated before), so this means that a 60px icon equals 40dp in the application.
Unless you are loading the files into memory each time you boot, use a database. Simple as that.
That is assuming that your colleges already have the program to handle queries to the files. If not, then use a database.