For me, plain old .contents()
appeared to work to return the text nodes, just have to be careful with your selectors so that you know they will be text nodes.
For example, this wrapped all the text content of the TDs in my table with pre
tags and had no problems.
jQuery("#resultTable td").content().wrap("<pre/>")
JPA's behaviour is correct (meaning as per the specification): objects aren't deleted simply because you've removed them from a OneToMany collection. There are vendor-specific extensions that do that but native JPA doesn't cater for it.
In part this is because JPA doesn't actually know if it should delete something removed from the collection. In object modeling terms, this is the difference between composition and "aggregation*.
In composition, the child entity has no existence without the parent. A classic example is between House and Room. Delete the House and the Rooms go too.
Aggregation is a looser kind of association and is typified by Course and Student. Delete the Course and the Student still exists (probably in other Courses).
So you need to either use vendor-specific extensions to force this behaviour (if available) or explicitly delete the child AND remove it from the parent's collection.
I'm aware of:
My favorite method:
CONTAINER_ID=$(docker ps | grep <string> | awk '{ print $1 }' | xargs docker inspect -f '{{.Id}}')
mv -f file.txt /var/lib/docker/devicemapper/mnt/$CONTAINER_ID/rootfs/root/file.txt
or
mv -f file.txt /var/lib/docker/aufs/mnt/$CONTAINER_ID/rootfs/root/file.txt
Finally, I've defeated my CiSCO EAP-FAST corporate wifi network, and all our Android devices are now able to connect to it.
The walk-around I've performed in order to gain access to this kind of networks from an Android device are easiest than you can imagine.
There's a Wifi Config Editor in the Google Play Store you can use to "activate" the secondary CISCO Protocols when you are setting up a EAP wifi connection.
Its name is Wifi Config Advanced Editor.
First, you have to setup your wireless network manually as close as you can to your "official" corporate wifi parameters.
Save it.
Go to the WCE and edit the parameters of the network you have created in the previous step.
There are 3 or 4 series of settings you should activate in order to force the Android device to use them as a way to connect (the main site I think you want to visit is Enterprise Configuration, but don't forget to check all the parameters to change them if needed.
As a suggestion, even if you have a WPA2 EAP-FAST Cipher, try LEAP in your setup. It worked for me as a charm.
When you finished to edit the config, go to the main Android wifi controller, and force to connect to this network.
Do not Edit the network again with the Android wifi interface.
I have tested it on Samsung Galaxy 1 and 2, Note mobile devices, and on a Lenovo Thinkpad Tablet.
I do this with a one liner:
val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, uri)
Which in the onActivityResult looks like:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_IMAGE_PICKER ) {
data?.data?.let { imgUri: Uri ->
val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, imgUri)
}
}
}
Access the property within the object id like that user._id.$oid
.
The data
variable contains a Buffer
object. Convert it into ASCII encoding using the following syntax:
data.toString('ascii', 0, data.length)
Asynchronously:
fs.readFile('test.txt', 'utf8', function (error, data) {
if (error) throw error;
console.log(data.toString());
});
To avoid an input with only spaces, use: "[a-zA-Z0-9]+[a-zA-Z0-9 ]+"
.
eg: abc | abc aBc | abc 123 AbC 938234
To ensure, for example, that a first AND last name are entered, use a slight variation like
"[a-zA-Z]+[ ][a-zA-Z]+"
eg: abc def
The following worked well for me
try {
asdf
} catch {
$string_err = $_ | Out-String
}
write-host $string_err
The result of this is the following as a string instead of an ErrorRecord object
asdf : The term 'asdf' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At C:\Users\TASaif\Desktop\tmp\catch_exceptions.ps1:2 char:5
+ asdf
+ ~~~~
+ CategoryInfo : ObjectNotFound: (asdf:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
Just create your own action.
namespace WpfUtil
{
using System.Reflection;
using System.Windows;
using System.Windows.Interactivity;
/// <summary>
/// Sets the designated property to the supplied value. TargetObject
/// optionally designates the object on which to set the property. If
/// TargetObject is not supplied then the property is set on the object
/// to which the trigger is attached.
/// </summary>
public class SetPropertyAction : TriggerAction<FrameworkElement>
{
// PropertyName DependencyProperty.
/// <summary>
/// The property to be executed in response to the trigger.
/// </summary>
public string PropertyName
{
get { return (string)GetValue(PropertyNameProperty); }
set { SetValue(PropertyNameProperty, value); }
}
public static readonly DependencyProperty PropertyNameProperty
= DependencyProperty.Register("PropertyName", typeof(string),
typeof(SetPropertyAction));
// PropertyValue DependencyProperty.
/// <summary>
/// The value to set the property to.
/// </summary>
public object PropertyValue
{
get { return GetValue(PropertyValueProperty); }
set { SetValue(PropertyValueProperty, value); }
}
public static readonly DependencyProperty PropertyValueProperty
= DependencyProperty.Register("PropertyValue", typeof(object),
typeof(SetPropertyAction));
// TargetObject DependencyProperty.
/// <summary>
/// Specifies the object upon which to set the property.
/// </summary>
public object TargetObject
{
get { return GetValue(TargetObjectProperty); }
set { SetValue(TargetObjectProperty, value); }
}
public static readonly DependencyProperty TargetObjectProperty
= DependencyProperty.Register("TargetObject", typeof(object),
typeof(SetPropertyAction));
// Private Implementation.
protected override void Invoke(object parameter)
{
object target = TargetObject ?? AssociatedObject;
PropertyInfo propertyInfo = target.GetType().GetProperty(
PropertyName,
BindingFlags.Instance|BindingFlags.Public
|BindingFlags.NonPublic|BindingFlags.InvokeMethod);
propertyInfo.SetValue(target, PropertyValue);
}
}
}
In this case I'm binding to a property called DialogResult on my viewmodel.
<Grid>
<Button>
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<wpf:SetPropertyAction PropertyName="DialogResult" TargetObject="{Binding}"
PropertyValue="{x:Static mvvm:DialogResult.Cancel}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
Cancel
</Button>
</Grid>
You can use a session object. It stores the cookies so you can make requests, and it handles the cookies for you
s = requests.Session()
# all cookies received will be stored in the session object
s.post('http://www...',data=payload)
s.get('http://www...')
Docs: https://requests.readthedocs.io/en/master/user/advanced/#session-objects
You can also save the cookie data to an external file, and then reload them to keep session persistent without having to login every time you run the script:
I've used this library before which does a pretty good job of what you're after. Specifically:-
qs.contains(name)
Returns true if the querystring has a parameter name, else false.
if (qs2.contains("name1")){ alert(qs2.get("name1"));}
Here is my little extension I just wrote to check if my delegate array contains a delegate object or not (Swift 2). :) It Also works with value types like a charm.
extension Array
{
func containsObject(object: Any) -> Bool
{
if let anObject: AnyObject = object as? AnyObject
{
for obj in self
{
if let anObj: AnyObject = obj as? AnyObject
{
if anObj === anObject { return true }
}
}
}
return false
}
}
If you have an idea how to optimize this code, than just let me know.
Android SDK implementation of FragmentTransaction wants an Animator
while support library wants an Animation
, don't ask me why but after strangeluk's comment I looked into android 4.0.3 code and support library.
Android SDK uses loadAnimator()
and support library uses loadAnimation()
Ensure the database's backup mode is set to Simple (see here for an overview of the different modes). This will avoid SQL Server waiting for a transaction log backup before reusing space.
Use dbcc shrinkfile
or Management Studio to shrink the log files.
Step #2 will do nothing until the backup mode is set.
I'm Using the fix, Because Using Knockout in MVC5 views.
On action
return Json(ModelHelper.GetJsonModel<Core_User>(viewModel));
function
public static TEntity GetJsonModel<TEntity>(TEntity Entity) where TEntity : class
{
TEntity Entity_ = Activator.CreateInstance(typeof(TEntity)) as TEntity;
foreach (var item in Entity.GetType().GetProperties())
{
if (item.PropertyType.ToString().IndexOf("Generic.ICollection") == -1 && item.PropertyType.ToString().IndexOf("SaymenCore.DAL.") == -1)
item.SetValue(Entity_, Entity.GetPropValue(item.Name));
}
return Entity_;
}
**@page {
margin-top:21% !important;
@top-left{
content: element(header);
}
@bottom-left {
content: element(footer
}
div.header {
position: running(header);
}
div.footer {
position: running(footer);
border-bottom: 2px solid black;
}
.pagenumber:before {
content: counter(page);
}
.pagecount:before {
content: counter(pages);
}
<div class="footer" style="font-size:12pt; font-family: Arial; font-family: Arial;">
<span>Page <span class="pagenumber"/> of <span class="pagecount"/></span>
</div >**
This sometimes happens when a string is converted from Windows-1252 to UTF-8 twice.
We had this in a Zend/PHP/MySQL application where characters like that were appearing in the database, probably due to the MySQL connection not specifying the correct character set. We had to:
Ensure Zend and PHP were communicating with the database in UTF-8 (was not by default)
Repair the broken characters with several SQL queries like this...
UPDATE MyTable SET
MyField1 = CONVERT(CAST(CONVERT(MyField1 USING latin1) AS BINARY) USING utf8),
MyField2 = CONVERT(CAST(CONVERT(MyField2 USING latin1) AS BINARY) USING utf8);
Do this for as many tables/columns as necessary.
You can also fix some of these strings in PHP if necessary. Note that because characters have been encoded twice, we actually need to do a reverse conversion from UTF-8 back to Windows-1252, which confused me at first.
mb_convert_encoding('’', 'Windows-1252', 'UTF-8'); // returns ’
you are going to want to separate your arguments into separate parameter
$msbuild = "C:\WINDOWS\Microsoft.NET\Framework\v3.5\MSBuild.exe"
$arguments = "/v:q /nologo"
start-process $msbuild $arguments
This will give you a list of a single group, and the members of each group.
param
(
[Parameter(Mandatory=$true,position=0)]
[String]$GroupName
)
import-module activedirectory
# optional, add a wild card..
# $groups = $groups + "*"
$Groups = Get-ADGroup -filter {Name -like $GroupName} | Select-Object Name
ForEach ($Group in $Groups)
{write-host " "
write-host "$($group.name)"
write-host "----------------------------"
Get-ADGroupMember -identity $($groupname) -recursive | Select-Object samaccountname
}
write-host "Export Complete"
If you want the friendly name, or other details, add them to the end of the select-object query.
Read this and try, this will help you:
Table1
column11,column12,column13,column14
Table2
column21,column22,column23,column24
SELECT table1.column11,table1.column12,table2asnew1.column21,table2asnew2.column21
FROM table1 INNER JOIN table2 AS table2asnew1 ON table1.column11=table2asnew1.column21 INNER TABLE table2 as table2asnew2 ON table1.column12=table2asnew2.column22
table2asnew1
is an instance of table 2 which is matched by table1.column11=table2asnew1.column21
and
table2asnew2
is another instance of table 2 which is matched by table1.column12=table2asnew2.column22
The iBeacon output power is measured (calibrated) at a distance of 1 meter. Let's suppose that this is -59 dBm (just an example). The iBeacon will include this number as part of its LE advertisment.
The listening device (iPhone, etc), will measure the RSSI of the device. Let's suppose, for example, that this is, say, -72 dBm.
Since these numbers are in dBm, the ratio of the power is actually the difference in dB. So:
ratio_dB = txCalibratedPower - RSSI
To convert that into a linear ratio, we use the standard formula for dB:
ratio_linear = 10 ^ (ratio_dB / 10)
If we assume conservation of energy, then the signal strength must fall off as 1/r^2. So:
power = power_at_1_meter / r^2
. Solving for r, we get:
r = sqrt(ratio_linear)
In Javascript, the code would look like this:
function getRange(txCalibratedPower, rssi) {
var ratio_db = txCalibratedPower - rssi;
var ratio_linear = Math.pow(10, ratio_db / 10);
var r = Math.sqrt(ratio_linear);
return r;
}
Note, that, if you're inside a steel building, then perhaps there will be internal reflections that make the signal decay slower than 1/r^2. If the signal passes through a human body (water) then the signal will be attenuated. It's very likely that the antenna doesn't have equal gain in all directions. Metal objects in the room may create strange interference patterns. Etc, etc... YMMV.
In my case, I have XCode6, the specified class .m file end up in the wrong place in build phase - It should have been under Compile Sources, but end up in the
HTML structure
<div id="app">
<div class="box">
<div class="title">How to preview link with iframe and javascript?</div>
<div class="note"><small>Note: Click to every link on content below to preview</small></div>
<div id="content">
We'll first attach all the events to all the links for which we want to <a href="https://htmlcssdownload.com/">preview</a> with the addEventListener method. In this method we will create elements including the floating frame containing the preview pane, the preview pane off button, the iframe button to load the preview content.
</div>
<h3>Preview the link</h3>
<div id="result"></div>
</div>
We'll first attach all the events to all the links for which we want to preview with the addEventListener method. In this method we will create elements including the floating frame containing the preview pane, the preview pane off button, the iframe button to load the preview content.
<script type="text/javascript">
(()=>{
let content = document.getElementById('content');
let links = content.getElementsByTagName('a');
for (let index = 0; index < links.length; index++) {
const element = links[index];
element.addEventListener('click',(e)=>{
e.preventDefault();
openDemoLink(e.target.href);
})
}
function openDemoLink(link){
let div = document.createElement('div');
div.classList.add('preview_frame');
let frame = document.createElement('iframe');
frame.src = link;
let close = document.createElement('a');
close.classList.add('close-btn');
close.innerHTML = "Click here to close the example";
close.addEventListener('click', function(e){
div.remove();
})
div.appendChild(frame);
div.appendChild(close);
document.getElementById('result').appendChild(div);
}
})()
To see detail at How to live preview link
Roll your own toFixed
function: for positive values Math.floor
works fine.
function toFixed(num, fixed) {
fixed = fixed || 0;
fixed = Math.pow(10, fixed);
return Math.floor(num * fixed) / fixed;
}
For negative values Math.floor
is round of the values. So you can use Math.ceil
instead.
Example,
Math.ceil(-15.778665 * 10000) / 10000 = -15.7786
Math.floor(-15.778665 * 10000) / 10000 = -15.7787 // wrong.
using jQuery 1.8 and above, should use the following:
var request = $.ajax({
type: 'POST',
url: 'mmm.php',
data: { abc: "abcdefghijklmnopqrstuvwxyz" } })
.done(function(data) { alert("success"+data.slice(0, 100)); })
.fail(function() { alert("error"); })
.always(function() { alert("complete"); });
check out the docs as @hitautodestruct stated.
You can't add an icon and text because you can't apply a different font to part of a placeholder, however, if you are satisfied with just an icon then it can work. The FontAwesome icons are just characters with a custom font (you can look at the FontAwesome Cheatsheet for the escaped Unicode character in the content
rule. In the less source code it's found in variables.less The challenge would be to swap the fonts when the input is not empty. Combine it with jQuery like this.
<form role="form">
<div class="form-group">
<input type="text" class="form-control empty" id="iconified" placeholder=""/>
</div>
</form>
With this CSS:
input.empty {
font-family: FontAwesome;
font-style: normal;
font-weight: normal;
text-decoration: inherit;
}
And this (simple) jQuery
$('#iconified').on('keyup', function() {
var input = $(this);
if(input.val().length === 0) {
input.addClass('empty');
} else {
input.removeClass('empty');
}
});
The transition between fonts will not be smooth, however.
You could not iterate or store more data than the length of your array. In this case you could do like this:
for (int i = 0; i <= name.length - 1; i++) {
// ....
}
Or this:
for (int i = 0; i < name.length; i++) {
// ...
}
Normally speaking you'd use a DB manager application like pgAdmin, browse to the object you're interested in, and right click your way to "script as create" or similar.
Are you trying to do this... without a management app?
The call to InitializeComponent()
(which is usually called in the default constructor of at least Window
and UserControl
) is actually a method call to the partial class of the control (rather than a call up the object hierarchy as I first expected).
This method locates a URI to the XAML for the Window
/UserControl
that is loading, and passes it to the System.Windows.Application.LoadComponent()
static method. LoadComponent()
loads the XAML file that is located at the passed in URI, and converts it to an instance of the object that is specified by the root element of the XAML file.
In more detail, LoadComponent
creates an instance of the XamlParser
, and builds a tree of the XAML. Each node is parsed by the XamlParser.ProcessXamlNode()
. This gets passed to the BamlRecordWriter
class. Some time after this I get a bit lost in how the BAML is converted to objects, but this may be enough to help you on the path to enlightenment.
Note: Interestingly, the InitializeComponent
is a method on the System.Windows.Markup.IComponentConnector
interface, of which Window
/UserControl
implement in the partial generated class.
Hope this helps!
Quite a few answers here recommend adding the slf4j-simple dependency to your maven pom file. You might want to check for the most current version.
At https://mvnrepository.com/artifact/org.slf4j/slf4j-simple you'll find the latest version of the SLF4J Simple Binding. Pick the one that suites you best (still 1.7.30 from 2019-12 is the stable version as of 2020-10) and include it to your pom.xml.
For your convenience some dependencies are shown here - but they might not be up-to-date when you read this!
Alpha Version of 2019-10
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-simple -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>2.0.0-alpha1</version>
</dependency>
Beta Version of Feb 2019
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-simple -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.8.0-beta4</version>
</dependency>
Stable Version 2019-12
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-simple -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.30</version>
</dependency>
I removed the scope test part thanks to the comment below.
snippet to retrieve json data, password protected
import requests
username = "my_user_name"
password = "my_super_secret"
url = "https://www.my_base_url.com"
the_page_i_want = "/my_json_data_page"
session = requests.Session()
# retrieve cookie value
resp = session.get(url+'/login')
csrf_token = resp.cookies['csrftoken']
# login, add referer
resp = session.post(url+"/login",
data={
'username': username,
'password': password,
'csrfmiddlewaretoken': csrf_token,
'next': the_page_i_want,
},
headers=dict(Referer=url+"/login"))
print(resp.json())
doesnt directly answer your question. But helpful for those who want to start something after some time.
Future.delayed(Duration(seconds: 1), () {
print('yo hey');
});
To use latest Async/Await features
https://www.npmjs.com/package/request-promise-native
npm install --save request
npm install --save request-promise-native
//code
async function getData (){
try{
var rp = require ('request-promise-native');
var options = {
uri:'https://reqres.in/api/users/2',
json:true
};
var response = await rp(options);
return response;
}catch(error){
throw error;
}
}
try{
console.log(getData());
}catch(error){
console.log(error);
}
I found that having too many and's would return incorrect results (for .NET 1.1 anyway)
DataRow[] results = table.Select("A = 'foo' AND B = 'bar' AND C = 'baz' and D ='fred' and E = 'marg'");
In my case A was the 12th field in a table and the select was effectively ignoring it.
However if I did
DataRow[] results = table.Select("A = 'foo' AND (B = 'bar' AND C = 'baz' and D ='fred' and E = 'marg')");
The filter worked correctly!
why not simply eg
var newList = list1.Union(list2)/*.Distinct()*//*.ToList()*/;
oh ... according to the documentation you can leave out the .Distinct()
This method excludes duplicates from the return set
Most answers missing an important point like if you have created csv
file exported from Microsoft Excel on windows and importing the same in linux environment, you will get unexpected result.
the correct syntax would be
load data local infile 'file.csv' into table table fields terminated by ',' enclosed by '"' lines terminated by '\r\n'
here the difference is '\r\n'
as against simply '\n
If you pass the -v
flag to the ansible-playbook command, then ansible will show the output on your terminal.
For your use case, you may want to try using the fetch module to copy the public key from the server to your local machine. That way, it will only show a "changed" status when the file changes.
This will get you the row count, but will leave the data reader at the end.
dataReader.Cast<object>().Count();
From a cmd:
&
is escaped like this: ^&
(based on @Wael Dalloul's answer)%
does not need to be escapedAn example:
start http://www.google.com/search?client=opera^&rls=en^&q=escape+ampersand%20and%20percentage+in+cmd^&sourceid=opera^&ie=utf-8^&oe=utf-8
From a batch file
&
is escaped like this: ^&
(based on @Wael Dalloul's answer)%
is escaped like this: %%
(based on the OPs update)An example:
start http://www.google.com/search?client=opera^&rls=en^&q=escape+ampersand%%20and%%20percentage+in+batch+file^&sourceid=opera^&ie=utf-8^&oe=utf-8
TL;DR: Use __builtin
intrinsics instead; they might happen to help.
I was able to make gcc
4.8.4 (and even 4.7.3 on gcc.godbolt.org) generate optimal code for this by using __builtin_popcountll
which uses the same assembly instruction, but gets lucky and happens to make code that doesn't have an unexpectedly long loop-carried dependency because of the false dependency bug.
I am not 100% sure of my benchmarking code, but objdump
output seems to share my views. I use some other tricks (++i
vs i++
) to make the compiler unroll loop for me without any movl
instruction (strange behaviour, I must say).
Results:
Count: 20318230000 Elapsed: 0.411156 seconds Speed: 25.503118 GB/s
Benchmarking code:
#include <stdint.h>
#include <stddef.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
uint64_t builtin_popcnt(const uint64_t* buf, size_t len){
uint64_t cnt = 0;
for(size_t i = 0; i < len; ++i){
cnt += __builtin_popcountll(buf[i]);
}
return cnt;
}
int main(int argc, char** argv){
if(argc != 2){
printf("Usage: %s <buffer size in MB>\n", argv[0]);
return -1;
}
uint64_t size = atol(argv[1]) << 20;
uint64_t* buffer = (uint64_t*)malloc((size/8)*sizeof(*buffer));
// Spoil copy-on-write memory allocation on *nix
for (size_t i = 0; i < (size / 8); i++) {
buffer[i] = random();
}
uint64_t count = 0;
clock_t tic = clock();
for(size_t i = 0; i < 10000; ++i){
count += builtin_popcnt(buffer, size/8);
}
clock_t toc = clock();
printf("Count: %lu\tElapsed: %f seconds\tSpeed: %f GB/s\n", count, (double)(toc - tic) / CLOCKS_PER_SEC, ((10000.0*size)/(((double)(toc - tic)*1e+9) / CLOCKS_PER_SEC)));
return 0;
}
Compile options:
gcc --std=gnu99 -mpopcnt -O3 -funroll-loops -march=native bench.c -o bench
GCC version:
gcc (Ubuntu 4.8.4-2ubuntu1~14.04.1) 4.8.4
Linux kernel version:
3.19.0-58-generic
CPU information:
processor : 0
vendor_id : GenuineIntel
cpu family : 6
model : 70
model name : Intel(R) Core(TM) i7-4870HQ CPU @ 2.50 GHz
stepping : 1
microcode : 0xf
cpu MHz : 2494.226
cache size : 6144 KB
physical id : 0
siblings : 1
core id : 0
cpu cores : 1
apicid : 0
initial apicid : 0
fpu : yes
fpu_exception : yes
cpuid level : 13
wp : yes
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx rdtscp lm constant_tsc nopl xtopology nonstop_tsc eagerfpu pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm arat pln pts dtherm fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 invpcid xsaveopt
bugs :
bogomips : 4988.45
clflush size : 64
cache_alignment : 64
address sizes : 36 bits physical, 48 bits virtual
power management:
Here is the App Bit Web Server (PHP,MySQL,PMA)
It can run a variety of CMS like Wordpress, Joomla, Drupal, Prestashop, etc. Besides CMS can also run PHP frameworks like Code Igniter, YII, CakePHP, etc. It is the same as WAMP or LAMP or XAMPP on your computer or laptop, but this is for android devices with lighttpd instead of apache.
You can use date(t_stamp)
to get only the date part from a timestamp.
You can check the date() function in the docs
DATE(expr)
Extracts the date part of the date or datetime expression expr.
mysql> SELECT DATE('2003-12-31 01:02:03'); -> '2003-12-31'
This solved my problem, from preventign that an event gets fired by a children:
doSmth(){_x000D_
// what ever_x000D_
}
_x000D_
<div (click)="doSmth()">_x000D_
<div (click)="$event.stopPropagation()">_x000D_
<my-component></my-component>_x000D_
</div>_x000D_
</div>
_x000D_
If you are a Xamarin user, this is the solution:
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle); //always call superclass first
this.Window.AddFlags(WindowManagerFlags.KeepScreenOn);
LoadApplication(new App());
}
(Not an answer, but a very similar problem) I have Git Gui installed on a Windows system behind a proxy. Issuing 'git clone' from a Linux virtual machine running on the Windows system works, but Git Gui yields the 443 error mentioned in the heading.
To fix this, one must edit %USERPROFILE%\.gitconfig to add an [http] section:
[http]
postBuffer = 1000000000
proxy = the.proxy.address:the.proxy.port
sslcainfo = C:/Users/username/Documents/the.certificate.name.cer
Note that the path to the security certificate file has had its backslashes ('\') replaced by slashes ('/').
A global Mutex is not only to ensure to have only one instance of an application. I personally prefer using Microsoft.VisualBasic to ensure single instance application like described in What is the correct way to create a single-instance WPF application? (Dale Ragan answer)... I found that's easier to pass arguments received on new application startup to the initial single instance application.
But regarding some previous code in this thread, I would prefer to not create a Mutex each time I want to have a lock on it. It could be fine for a single instance application but in other usage it appears to me has overkill.
That's why I suggest this implementation instead:
Usage:
static MutexGlobal _globalMutex = null;
static MutexGlobal GlobalMutexAccessEMTP
{
get
{
if (_globalMutex == null)
{
_globalMutex = new MutexGlobal();
}
return _globalMutex;
}
}
using (GlobalMutexAccessEMTP.GetAwaiter())
{
...
}
Mutex Global Wrapper:
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Threading;
namespace HQ.Util.General.Threading
{
public class MutexGlobal : IDisposable
{
// ************************************************************************
public string Name { get; private set; }
internal Mutex Mutex { get; private set; }
public int DefaultTimeOut { get; set; }
public Func<int, bool> FuncTimeOutRetry { get; set; }
// ************************************************************************
public static MutexGlobal GetApplicationMutex(int defaultTimeOut = Timeout.Infinite)
{
return new MutexGlobal(defaultTimeOut, ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value);
}
// ************************************************************************
public MutexGlobal(int defaultTimeOut = Timeout.Infinite, string specificName = null)
{
try
{
if (string.IsNullOrEmpty(specificName))
{
Name = Guid.NewGuid().ToString();
}
else
{
Name = specificName;
}
Name = string.Format("Global\\{{{0}}}", Name);
DefaultTimeOut = defaultTimeOut;
FuncTimeOutRetry = DefaultFuncTimeOutRetry;
var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
var securitySettings = new MutexSecurity();
securitySettings.AddAccessRule(allowEveryoneRule);
Mutex = new Mutex(false, Name, out bool createdNew, securitySettings);
if (Mutex == null)
{
throw new Exception($"Unable to create mutex: {Name}");
}
}
catch (Exception ex)
{
Log.Log.Instance.AddEntry(Log.LogType.LogException, $"Unable to create Mutex: {Name}", ex);
throw;
}
}
// ************************************************************************
/// <summary>
///
/// </summary>
/// <param name="timeOut"></param>
/// <returns></returns>
public MutexGlobalAwaiter GetAwaiter(int timeOut)
{
return new MutexGlobalAwaiter(this, timeOut);
}
// ************************************************************************
/// <summary>
///
/// </summary>
/// <param name="timeOut"></param>
/// <returns></returns>
public MutexGlobalAwaiter GetAwaiter()
{
return new MutexGlobalAwaiter(this, DefaultTimeOut);
}
// ************************************************************************
/// <summary>
/// This method could either throw any user specific exception or return
/// true to retry. Otherwise, retruning false will let the thread continue
/// and you should verify the state of MutexGlobalAwaiter.HasTimedOut to
/// take proper action depending on timeout or not.
/// </summary>
/// <param name="timeOutUsed"></param>
/// <returns></returns>
private bool DefaultFuncTimeOutRetry(int timeOutUsed)
{
// throw new TimeoutException($"Mutex {Name} timed out {timeOutUsed}.");
Log.Log.Instance.AddEntry(Log.LogType.LogWarning, $"Mutex {Name} timeout: {timeOutUsed}.");
return true; // retry
}
// ************************************************************************
public void Dispose()
{
if (Mutex != null)
{
Mutex.ReleaseMutex();
Mutex.Close();
}
}
// ************************************************************************
}
}
Awaiter
using System;
namespace HQ.Util.General.Threading
{
public class MutexGlobalAwaiter : IDisposable
{
MutexGlobal _mutexGlobal = null;
public bool HasTimedOut { get; set; } = false;
internal MutexGlobalAwaiter(MutexGlobal mutexEx, int timeOut)
{
_mutexGlobal = mutexEx;
do
{
HasTimedOut = !_mutexGlobal.Mutex.WaitOne(timeOut, false);
if (! HasTimedOut) // Signal received
{
return;
}
} while (_mutexGlobal.FuncTimeOutRetry(timeOut));
}
#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
_mutexGlobal.Mutex.ReleaseMutex();
}
// TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
// TODO: set large fields to null.
disposedValue = true;
}
}
// TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
// ~MutexExAwaiter()
// {
// // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
// Dispose(false);
// }
// This code added to correctly implement the disposable pattern.
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
// TODO: uncomment the following line if the finalizer is overridden above.
// GC.SuppressFinalize(this);
}
#endregion
}
}
**
I hope this code is beneficial
**
String user = getResources().getString(R.string.muser);
var jArr = [
{
id : "001",
name : "apple",
category : "fruit",
color : "red"
},
{
id : "002",
name : "melon",
category : "fruit",
color : "green"
},
{
id : "003",
name : "banana",
category : "fruit",
color : "yellow"
}
]
var tableData = '<table><tr><td>Id</td><td>Name</td><td>Category</td><td>Color</td></tr>';
$.each(jArr, function(index, data) {
tableData += '<tr><td>'+data.id+'</td><td>'+data.name+'</td><td>'+data.category+'</td><td>'+data.color+'</td></tr>';
});
$('div').html(tableData);
merge
is used to bring two (or more) branches together.
a little example:
# on branch A:
# create new branch B
$ git checkout -b B
# hack hack
$ git commit -am "commit on branch B"
# create new branch C from A
$ git checkout -b C A
# hack hack
$ git commit -am "commit on branch C"
# go back to branch A
$ git checkout A
# hack hack
$ git commit -am "commit on branch A"
so now there are three separate branches (namely A B and C) with different heads
to get the changes from B and C back to A, checkout A (already done in this example) and then use the merge command:
# create an octopus merge
$ git merge B C
your history will then look something like this:
…-o-o-x-------A
|\ /|
| B---/ |
\ /
C---/
if you want to merge across repository/computer borders, have a look at git pull
command, e.g. from the pc with branch A (this example will create two new commits):
# pull branch B
$ git pull ssh://host/… B
# pull branch C
$ git pull ssh://host/… C
You need to set option CURLOPT_PROXYTYPE
to CURLPROXY_SOCKS5_HOSTNAME
, which sadly wasn't defined in old PHP versions, circa pre-5.6; if you have earlier in but you can explicitly use its value, which is equal to 7
:
curl_setopt($ch, CURLOPT_PROXYTYPE, 7);
There is now a beta available of Google Maps KML Importing Utility.
It is part of the Google Maps Android API Utility Library. As documented it allows loading KML files from streams
KmlLayer layer = new KmlLayer(getMap(), kmlInputStream, getApplicationContext());
or local resources
KmlLayer layer = new KmlLayer(getMap(), R.raw.kmlFile, getApplicationContext());
After you have created a KmlLayer, call addLayerToMap() to add the imported data onto the map.
layer.addLayerToMap();
Eclipse artifact searching depends on repository's index file. It seems you did not download the index file.
Go to Window -> Prefrences -> Maven and check "Download repository index updates on start". Restart Eclipse and then look at the progress view. An index file should be downloading.
After downloading completely, artifact searching will be ready to use.
UPDATE You also need to rebuild your Maven repository index in 'maven repository view'.
In this view , open 'Global Repositories', right-click 'central', check 'Full Index Enable', and then, click 'Rebuild Index' in the same menu.
A 66M index file will be downloaded.
As Paddy mentioned: if you use an overload of UrlHelper.Action()
that explicitly specifies the protocol to use, the generated URL will be absolute and fully qualified instead of being relative.
I wrote a blog post called How to build absolute action URLs using the UrlHelper class in which I suggest to write a custom extension method for the sake of readability:
/// <summary>
/// Generates a fully qualified URL to an action method by using
/// the specified action name, controller name and route values.
/// </summary>
/// <param name="url">The URL helper.</param>
/// <param name="actionName">The name of the action method.</param>
/// <param name="controllerName">The name of the controller.</param>
/// <param name="routeValues">The route values.</param>
/// <returns>The absolute URL.</returns>
public static string AbsoluteAction(this UrlHelper url,
string actionName, string controllerName, object routeValues = null)
{
string scheme = url.RequestContext.HttpContext.Request.Url.Scheme;
return url.Action(actionName, controllerName, routeValues, scheme);
}
You can then simply use it like that in your view:
@Url.AbsoluteAction("Action", "Controller")
netstat -nlp
should tell you the PID of what's listening on which port.
As of Hive 0.10 this patch-967 implements SHOW CREATE TABLE
which "shows the CREATE TABLE
statement that creates a given table, or the CREATE VIEW
statement that creates a given view."
Usage:
SHOW CREATE TABLE myTable;
With bootstrap 3 the best way to go about achieving what you want is ...with offsetting columns. Please see these examples for more detail:
http://getbootstrap.com/css/#grid-offsetting
In short, and without seeing your divs here's an example what might help, without using any custom classes. Just note how the "col-6" is used and how half of that is 3 ...so the "offset-3" is used. Splitting equally will allow the centered spacing you're going for:
<div class="container">
<div class="col-sm-6 col-sm-offset-3">
your centered, floating column
</div></div>
Feel free to disregard this solution as subtracting a list from an Index does not preserve the order of the original Index, if that's important.
In [61]: df.reindex(columns=pd.Index(['x', 'y']).append(df.columns - ['x', 'y']))
Out[61]:
x y a b
0 3 -1 1 2
1 6 -2 2 4
2 9 -3 3 6
3 12 -4 4 8
You have these options:
Collections.synchronizedList()
: you can wrap any List
implementation (ArrayList
, LinkedList
or a 3rd-party list). Access to every method (reading and writing) will be protected using synchronized
. When using iterator()
or enhanced for loop, you must manually synchronize the whole iteration. While iterating, other threads are fully blocked even from reading. You can also synchronize separately for each hasNext
and next
calls, but then ConcurrentModificationException
is possible.
CopyOnWriteArrayList
: it's expensive to modify, but wait-free to read. Iterators never throw ConcurrentModificationException
, they return a snapshot of the list at the moment of iterator creation even if the list is modified by another thread while iterating. Useful for infrequently updated lists. Bulk operations like addAll
are preferred for updates - the internal array is copied less many times.
Vector
: very much like synchronizedList(new ArrayList<>())
, but iteration is synchronized too. However, iterators can throw ConcurrentModificationException
if the vector is modified by another thread while iterating.
Other options:
Collections.unmodifiableList()
: lock-free, thread-safe, but non-modifiableList.of
& List.copyOf
: Another non-modifiable list in Java 9 and later.Queue
or Deque
might be an alternative if you only add/remove at the ends of the list and iterate the list. There's no access by index and no adding/removing at arbitrary places. They have multiple concurrent implementations with better performance and better concurrent access, but it's beyond the scope of this question. You can also have a look at JCTools, they contain more performant queue implementations specialized for single consumer or single producer.If infinity is a possible value, I would use numpy.isfinite
numpy.isfinite(myarray).all()
If the above evaluates to True
, then myarray
contains no, numpy.nan
, numpy.inf
or -numpy.inf
values.
numpy.nan
will be OK with numpy.inf
values, for example:
In [11]: import numpy as np
In [12]: b = np.array([[4, np.inf],[np.nan, -np.inf]])
In [13]: np.isnan(b)
Out[13]:
array([[False, False],
[ True, False]], dtype=bool)
In [14]: np.isfinite(b)
Out[14]:
array([[ True, False],
[False, False]], dtype=bool)
I'm always amazed that more people don't use ActiveState Komodo.
It has the best debugging facilities of any PHP IDE I have tried, is a very mature product and has more useful features than you can shake a stick at. Of note, it has a fantastic HTTP inspector, Javascript debugger and Regular Expression Toolkit. You can get it so that it steps through your PHP, then you see your Javascript running, and then see your HTTP traffic going out over the wire!
It also comes in free (Komodo Edit) and open (OpenKomodo versions).
Oh, and if you don't always hack just on PHP, it's designed as a multi-language editor and rocks for Ruby and Python too.
I've been a happy customer for around 5 years.
I'm not sure about your exact version, but Chrome has a tab "Network" with several items and when I click on them I can see the headers on the right in a tab.
Press F12 on windows or ??I on a mac to bring up the Chrome developer tools.
See this TechNet article: Runas command documentation
From a command prompt:
C:\> runas /user:<localmachinename>\administrator cmd
Or, if you're connected to a domain:
C:\> runas /user:<DomainName>\<AdministratorAccountName> cmd
In addition to the other answers, the fmod
documentation has some interesting things to say on the subject:
math.fmod(x, y)
Return
fmod(x, y)
, as defined by the platform C library. Note that the Python expressionx % y
may not return the same result. The intent of the C standard is thatfmod(x, y)
be exactly (mathematically; to infinite precision) equal tox - n*y
for some integer n such that the result has the same sign asx
and magnitude less thanabs(y)
. Python’sx % y
returns a result with the sign ofy
instead, and may not be exactly computable for float arguments. For example,fmod(-1e-100, 1e100)
is-1e-100
, but the result of Python’s-1e-100 % 1e100
is1e100-1e-100
, which cannot be represented exactly as a float, and rounds to the surprising1e100
. For this reason, functionfmod()
is generally preferred when working with floats, while Python’sx % y
is preferred when working with integers.
Lazy loading allows you to defer the association retrieval or to have a better control over the fetching strategy.
When you use EAGER loading, you define a global fetch plan which cannot be overridden at query time, meaning you are limited to a decision you took while designing your entity model. The EAGER fetching is a code smell, because the fetching strategy is a query-time policy and it might differ from a business use case to another.
The fetching strategy is a very important aspect, as too much EAGER fetching can cause serious performance related issues.
According to the RFC that introduced the operator, $a <=> $b
evaluates to:
$a == $b
$a < $b
$a > $b
which seems to be the case in practice in every scenario I've tried, although strictly the official docs only offer the slightly weaker guarantee that $a <=> $b
will return
an integer less than, equal to, or greater than zero when
$a
is respectively less than, equal to, or greater than$b
Regardless, why would you want such an operator? Again, the RFC addresses this - it's pretty much entirely to make it more convenient to write comparison functions for usort
(and the similar uasort
and uksort
).
usort
takes an array to sort as its first argument, and a user-defined comparison function as its second argument. It uses that comparison function to determine which of a pair of elements from the array is greater. The comparison function needs to return:
an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
The spaceship operator makes this succinct and convenient:
$things = [
[
'foo' => 5.5,
'bar' => 'abc'
],
[
'foo' => 7.7,
'bar' => 'xyz'
],
[
'foo' => 2.2,
'bar' => 'efg'
]
];
// Sort $things by 'foo' property, ascending
usort($things, function ($a, $b) {
return $a['foo'] <=> $b['foo'];
});
// Sort $things by 'bar' property, descending
usort($things, function ($a, $b) {
return $b['bar'] <=> $a['bar'];
});
More examples of comparison functions written using the spaceship operator can be found in the Usefulness section of the RFC.
From: http://java.sun.com/javase/6/docs/technotes/tools/windows/classpath.html
Class path entries can contain the basename wildcard character
*
, which is considered equivalent to specifying a list of all the files in the directory with the extension .jar or .JAR. For example, the class path entryfoo/*
specifies all JAR files in the directory named foo. A classpath entry consisting simply of*
expands to a list of all the jar files in the current directory.
This should work in Java6, not sure about Java5
(If it seems it does not work as expected, try putting quotes. eg: "foo/*"
)
To stop the Media Player without the risk of an Illegal State Exception, you must do
try {
mp.reset();
mp.prepare();
mp.stop();
mp.release();
mp=null;
}
catch (Exception e)
{
e.printStackTrace();
}
rather than just
try {
mp.stop();
mp.release();
mp=null;
}
catch (Exception e)
{
e.printStackTrace();
}
Just want to add (since I googled for this problem, and this question popped first) IE6 and other versions render PNG transparency very ugly. If you have PNG image that is alpha transparent (32bit) and want to show it over some complex background, you can never do this simply in IE. But you can display it correctly over a single colour background as long as you set that PNG images (or divs) CSS attribute background-color
to be the same as the parents background-color
.
So this will render black where image should be alpha transparent, and transparent where alpha byte is 0:
<div style="background-color: white;">
<div style="background-image: url(image.png);"/>
</div>
And this will render correctly (note the background-color attribute in the inner div):
<div style="background-color: white;">
<div style="background-color: white; background-image: url(image.png);"/>
</div>
Complex alternative to this which enables alpha image over a complex background is to use AlphaImageLoader
to load up and render image of the certain opacity. This works until you want to change that opacity... Problem in detail and its solution (javascript) can be found HERE.
I don't think you can do that. You can be in the middle of the document, however you don't know the toolbar layout or the size of the browser controls. Thus you can center in the document, but not in the middle of the browser window.
I had the same problem, It was solved when I checked the below checkbox
Include externals
I created a single node k8s cluster using kubeadm. When i tried PortForward and kubectl proxy, it showed external IP as pending.
$ kubectl get svc -n argocd argocd-server
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
argocd-server LoadBalancer 10.107.37.153 <pending> 80:30047/TCP,443:31307/TCP 110s
In my case I've patched the service like this:
kubectl patch svc <svc-name> -n <namespace> -p '{"spec": {"type": "LoadBalancer", "externalIPs":["172.31.71.218"]}}'
After this, it started serving over the public IP
$ kubectl get svc argo-ui -n argo
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
argo-ui LoadBalancer 10.103.219.8 172.31.71.218 80:30981/TCP 7m50s
The new Grid CSS specification provides a far more elegant solution. Using position: absolute
may lead to overlaps or scaling issues while Grid will save you from dirty CSS hacks.
Most minimal Grid Overlay example:
HTML
<div class="container">
<div class="content">This is the content</div>
<div class="overlay">Overlay - must be placed under content in the HTML</div>
</div>
CSS
.container {
display: grid;
}
.content, .overlay {
grid-area: 1 / 1;
}
That's it. If you don't build for Internet Explorer, your code will most probably work.
MongoDB needs data directory to store data.
Default path is /data/db
When you start MongoDB engine, it searches this directory which is missing in your case. Solution is create this directory and assign rwx
permission to user.
If you want to change the path of your data directory then you should specify it while starting mongod server like,
mongod --dbpath /data/<path> --port <port no>
This should help you start your mongod server with custom path and port.
Not to repeat what everyone already have said but keep the following cheat sheet handly for File manipulations:
System.IO.File.ReadAllBytes(filename);
File.Exists(filename)
Path.Combine(folderName, resOfThePath);
Path.GetFullPath(path); // converts a relative path to absolute one
Path.GetExtension(path);
You can shorten JSprangs solution a bit by using a method group instead:
string s1 = "1;2;3;4;5;6;7;8;9;10;11;12";
int[] ints = s1.Split(';').Select(int.Parse).ToArray();
You need to use cat
to get the contents of the file named 'DSC_0251.JPG', rather than the filename itself.
test="$(cat DSC_0251.JPG | base64)"
However, base64
can read from the file itself:
test=$( base64 DSC_0251.JPG )
xcopy e:\source_folder f:\destination_folder /e /i /h
The /h is just in case there are hidden files. The /i creates a destination folder if there are muliple source files.
f = open("test.py", "a") Will be created in whatever directory the python file is run from.
I'm not sure about the other error...I don't work in windows.
You have to specify the format (fmt
) of you data in savetxt
, in this case as a string (%s
):
num.savetxt('test.txt', DAT, delimiter=" ", fmt="%s")
The default format is a float, that is the reason it was expecting a float instead of a string and explains the error message.
Hey I just had this problem and found that I wasn't looking at the folder location closely enough:
I had
require_once /vagrant/public/liberate/**APP**/vendor/autoload.php
What worked was:
require_once /vagrant/public/liberate/vendor/autoload.php
It was very easy (as a beginner) to overlook this very unnoticeable issue. Yes I do realize that the require issue being logged points directly to the issue at hand, but if you are a beginner, like me, these things can be easily overlooked.
FIX:
Have a good look at the debug of ( __ Dir __ '/etc/etc/etc/file.php') then have your file system open in a different window, and map the two directly. If there is even the slightest difference this require will not work and the above error will be spat out.
This will give you the count per month for 2012;
SELECT MONTH(ARR_DATE) MONTH, COUNT(*) COUNT
FROM table_emp
WHERE YEAR(arr_date)=2012
GROUP BY MONTH(ARR_DATE);
Demo here.
Add the function ob_end_clean(); before call the Output function. It worked for me within a custom Wordpress function!
ob_end_clean();
$pdf->Output($pdf_name, 'I');
I use the following:
double x = Math.Truncate(myDoubleValue * 100) / 100;
For instance:
If the number is 50.947563 and you use the following, the following will happen:
- Math.Truncate(50.947563 * 100) / 100;
- Math.Truncate(5094.7563) / 100;
- 5094 / 100
- 50.94
And there's your answer truncated, now to format the string simply do the following:
string s = string.Format("{0:N2}%", x); // No fear of rounding and takes the default number format
Second approach is object initializer in C#
Object initializers let you assign values to any accessible fields or properties of an object at creation time without having to explicitly invoke a constructor.
The first approach
var albumData = new Album("Albumius", "Artistus", 2013);
explicitly calls the constructor, whereas in second approach constructor call is implicit. With object initializer you can leave out some properties as well. Like:
var albumData = new Album
{
Name = "Albumius",
};
Object initializer would translate into something like:
var albumData;
var temp = new Album();
temp.Name = "Albumius";
temp.Artist = "Artistus";
temp.Year = 2013;
albumData = temp;
Why it uses a temporary object (in debug mode) is answered here by Jon Skeet.
As far as advantages for both approaches are concerned, IMO, object initializer would be easier to use specially if you don't want to initialize all the fields. As far as performance difference is concerned, I don't think there would any since object initializer calls the parameter less constructor and then assign the properties. Even if there is going to be performance difference it should be negligible.
You need to make the object first, then use []
to set it.
var key = "happyCount";
var obj = {};
obj[key] = someValueArray;
myArray.push(obj);
UPDATE 2018:
If you're able to use ES6 and Babel, you can use this new feature:
{
[yourKeyVariable]: someValueArray,
}
public FileContentResult GetImage(int productId) {
Product prod = repository.Products.FirstOrDefault(p => p.ProductID == productId);
if (prod != null) {
return File(prod.ImageData, prod.ImageMimeType);
} else {
return null;
}
}
If you need only one upper case and special character then this should work:
@"^(?=.{8,}$)(?=[^A-Z]*[A-Z][^A-Z]*$)\w*\W\w*$"
For anyone else who stumbles across this thread but needs to find or create an object with attributes that might change depending on the circumstances, add the following method to your model:
# Return the first object which matches the attributes hash
# - or -
# Create new object with the given attributes
#
def self.find_or_create(attributes)
Model.where(attributes).first || Model.create(attributes)
end
Optimization tip: regardless of which solution you choose, consider adding indexes for the attributes you are querying most frequently.
I had this issue occurring with mailto:
and tel:
links inside an iframe (in Chrome, not a webview). Clicking the links would show the grey "page not found" page and inspecting the page showed it had a ERR_UNKNOWN_URL_SCHEME error.
Adding target="_blank"
, as suggested by this discussion of the issue fixed the problem for me.
This script runs on Git Bash (MINGW64) on Windows and return a messages depending of the ping result.
#!/bin/bash
#$1 should be something like "19.62.55"
if [ -z "$1" ]
then
echo "No identify of the network supplied, i.e. 19.62.55"
else
ipAddress=$1
for i in {1..256} ;do
(
{
ping -w 5 $ipAddress.$i ;
result=$(echo $?);
} &> /dev/null
if [ $result = 0 ]; then
echo Successful Ping From : $ipAddress.$i
else
echo Failed Ping From : $ipAddress.$i
fi &);
done
fi
This solution works for arbitrary nesting depths - not just the "list of lists" depth that some (all?) of the other solutions are limited to:
def flatten(x):
result = []
for el in x:
if hasattr(el, "__iter__") and not isinstance(el, basestring):
result.extend(flatten(el))
else:
result.append(el)
return result
It's the recursion which allows for arbitrary depth nesting - until you hit the maximum recursion depth, of course...
You could use OHHTTPStubs and stub the network requests to specific URLs to fail.
I found that running the npm install
command in the same directory where your Angular project is, eliminates these warnings. I do not know the reason why.
Specifically, I was trying to use ng2-completer
$ npm install ng2-completer --save
npm WARN saveError ENOENT: no such file or directory, open 'C:\Work\foo\package.json'
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN enoent ENOENT: no such file or directory, open 'C:\Work\foo\package.json'
npm WARN [email protected] requires a peer of @angular/common@>= 6.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of @angular/core@>= 6.0.0 but noneis installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of @angular/forms@>= 6.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN foo No description
npm WARN foo No repository field.
npm WARN foo No README data
npm WARN foo No license field.
I was unable to compile. When I tried again, this time in my Angular project directory which was in foo/foo_app, it worked fine.
cd foo/foo_app
$ npm install ng2-completer --save
in 2020 if you want to set active class on element which has no [routerLink] - you can do simply:
<a
(click)="bookmarks()"
[class.active]="router.isActive('/string/path/'+you+'/need', false)" // <== you need this one. second argument 'false' - exact: true/false
routerLinkActive="active"
[routerLinkActiveOptions]="{ exact: true }"
>
bookmarks
</a>
in Xcode 4.5 using storyboard, by far the easiest solution i've found when the value of the Back button doesn't have to change dynamically is to use the "Back Button" field associated with the Navigation Item of the View Controller to which you want the "Back" button to say something else.
e.g. in the screenshot below, i want the Back button for the view controller(s) that i push to have "Back" as the title of the Back button.
of course, this won't work if you need the back button to say something slightly different each time … there are all of the other solutions here for that.
1) For me that's the most simple way passing parameters to async task is like this
// To call the async task do it like this
Boolean[] myTaskParams = { true, true, true };
myAsyncTask = new myAsyncTask ().execute(myTaskParams);
Declare and use the async task like here
private class myAsyncTask extends AsyncTask<Boolean, Void, Void> {
@Override
protected Void doInBackground(Boolean...pParams)
{
Boolean param1, param2, param3;
//
param1=pParams[0];
param2=pParams[1];
param3=pParams[2];
....
}
2) Passing methods to async-task In order to avoid coding the async-Task infrastructure (thread, messagenhandler, ...) multiple times you might consider to pass the methods which should be executed in your async-task as a parameter. Following example outlines this approach. In addition you might have the need to subclass the async-task to pass initialization parameters in the constructor.
/* Generic Async Task */
interface MyGenericMethod {
int execute(String param);
}
protected class testtask extends AsyncTask<MyGenericMethod, Void, Void>
{
public String mParam; // member variable to parameterize the function
@Override
protected Void doInBackground(MyGenericMethod... params) {
// do something here
params[0].execute("Myparameter");
return null;
}
}
// to start the asynctask do something like that
public void startAsyncTask()
{
//
AsyncTask<MyGenericMethod, Void, Void> mytest = new testtask().execute(new MyGenericMethod() {
public int execute(String param) {
//body
return 1;
}
});
}
i wrote a simple function for this:
Function (stringVar param)
(
Local stringVar oneChar := '0';
Local numberVar strLen := Length(param);
Local numberVar index := strLen;
oneChar = param[strLen];
while index > 0 and oneChar = '0' do
(
oneChar := param[index];
index := index - 1;
);
Left(param , index + 1);
)
You started with ManyToOne mapping , then you put OneToMany mapping as well for BiDirectional way. Then at OneToMany side (usually your parent table/class), you have to mention "mappedBy" (mapping is done by and in child table/class), so hibernate will not create EXTRA mapping table in DB (like TableName = parent_child).
this:
element.setAttribute("onclick", alert("blabla"));
should be:
element.onclick = function () {
alert("blabla");
}
Because you call alert instead push alert as string in attribute
You can also check contents of *.tag.gz file using pigz
(parallel gzip) to speedup the archive check:
pigz -cvdp number_of_threads /[...]path[...]/archive_name.tar.gz | tar -tv > /dev/null
Probably the fastest way to access the PHP.ini for the currently loaded version of PHP in MAMP PRO (v.4.2.1):
It's likely that the download was corrupted if you are getting an error with the disk image. Go back to the downloads page at https://developers.google.com/appengine/downloads and look at the SHA1 checksum. Then, go to your Terminal app on your mac and run the following:
openssl sha1 [put the full path to the file here without brackets]
For example:
openssl sha1 /Users/me/Desktop/myFile.dmg
If you get a different value than the one on the Downloads page, you know your file is not properly downloaded and you should try again.
Even if you don't control the server, you can still see the error messages by adding the following line to the Web.config file in your project (bewlow <system.web>
):
<customErrors mode="off" />
---
- hosts: all
tasks:
- name: Gather Version
debug:
msg: "The server Operating system is {{ ansible_distribution }} {{ ansible_distribution_major_version }}"
- name: Write Version
local_action: shell echo "This is {{ ansible_distribution }} {{ ansible_distribution_major_version }}" >> /tmp/output
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:
There a lot of answers, but I don't see any complete solutions. The problem with the accepted answer, as well as enum { this, one }
, is that it disperses the string value you happen to be using through many files. I don't really like the "update" either, it's complex and doesn't leverage types as well. I think Michael Bromley's answer is most correct, but it's interface is a bit of a hassle and could do with a type.
I am using TypeScript 2.0.+ ... Here's what I would do
export type Greeting = "hello" | "world";
export const Greeting : { hello: Greeting , world: Greeting } = {
hello: "hello",
world: "world"
};
Then use like this:
let greet: Greeting = Greeting.hello
It also has much nicer type / hover-over information when using a helpful IDE. The draw back is you have to write the strings twice, but at least it's only in two places.
After doing all of above I still couldn't login as root
remotely, but Telnetting to port 3306
confirmed that MySQL
was accepting connections.
I started looking at the users in MySQL and noticed there were multiple root users with different passwords.
select user, host, password from mysql.user;
So in MySQL
I set all the passwords for root again and I could finally log in remotely as root
.
use mysql;
update user set password=PASSWORD('NEWPASSWORD') where User='root';
flush privileges;
You can. Try something like this:
@Path("/todo/{varX}/{varY}")
@Produces({"application/xml", "application/json"})
public Todo whatEverNameYouLike(@PathParam("varX") String varX,
@PathParam("varY") String varY) {
Todo todo = new Todo();
todo.setSummary(varX);
todo.setDescription(varY);
return todo;
}
Then call your service with this URL;
http://localhost:8088/JerseyJAXB/rest/todo/summary/description
I had a similar problem, trying to add a background image with inline css. No need to specify the images folder due to the way asset sync works.
This worked for me:
background-image: url('/assets/image.jpg');
Collection is an interface from which other class forms like List, Set are derived. Collections (with "S") is a utility class having static methods to simplify work on collection. Ex : Collections.sort()
I was just looking for a smiliar issue and I found this:
.div{
height : 100vh;
}
more info
vw: 1/100th viewport width
vh: 1/100th viewport height
vmin: 1/100th of the smallest side
vmax: 1/100th of the largest side
It might also be (which was the case for my colleague) that you have disabled automatic loading of symbols for whichever reason.
If so, reenable it by opening Tools -> Options -> Debugging -> Symbols
and move the radiobutton to "Load all modules, unless excluded"
User $()
to get jQuery
object from your link and data()
to get your values
<a id="option1"
data-id="10"
data-option="21"
href="#"
onclick="goDoSomething($(this).data('id'),$(this).data('option'));">
Click to do something
</a>
Do the following, download SQLLite Database Browser from here:
Locate your db. file in your phone.
Then, as soon you install the program go to: "Browse Data", you will see all the SMS there!!
You can actually export the data to an excel file or SQL.
As an aid to understanding why extending an Enum is not reasonable at the language implementation level to consider what would happen if you passed an instance of the extended Enum to a routine that only understands the base Enum. A switch that the compiler promised had all cases covered would in fact not cover those extended Enum values.
This further emphasizes that Java Enum values are not integers such as C's are, for instances: to use a Java Enum as an array index you must explicitly ask for its ordinal() member, to give a java Enum an arbitrary integer value you must add an explicit field for that and reference that named member.
This is not a comment on the OP's desire, just on why Java ain't never going to do it.
If you mean you are only getting a null return when you use NUnit, then you probably need to copy the ConnectionString value the your app.config of your application to the app.config of your test library.
When it is run by the test loader, the test assembly is loaded at runtime and will look in its own app.config (renamed to testAssembly.dll.config at compile time) rather then your applications config file.
To get the location of the assembly you're running, try
System.Reflection.Assembly.GetExecutingAssembly().Location
grep's -A 1
option will give you one line after; -B 1
will give you one line before; and -C 1
combines both to give you one line both before and after, -1
does the same.
function createDateRangeArray($start, $end) {
// Modified by JJ Geewax
$range = array();
if (is_string($start) === true) $start = strtotime($start);
if (is_string($end) === true ) $end = strtotime($end);
if ($start > $end) return createDateRangeArray($end, $start);
do {
$range[] = date('Y-m-d', $start);
$start = strtotime("+ 1 day", $start);
}
while($start < $end);
return $range;
}
Source: http://boonedocks.net/mike/archives/137-Creating-a-Date-Range-Array-with-PHP.html
You need also $sce.trustAsResourceUrl
or it won't open the website inside the iframe:
angular.module('myApp', [])_x000D_
.controller('dummy', ['$scope', '$sce', function ($scope, $sce) {_x000D_
_x000D_
$scope.url = $sce.trustAsResourceUrl('https://www.angularjs.org');_x000D_
_x000D_
$scope.changeIt = function () {_x000D_
$scope.url = $sce.trustAsResourceUrl('https://docs.angularjs.org/tutorial');_x000D_
}_x000D_
}]);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
_x000D_
<div ng-app="myApp" ng-controller="dummy">_x000D_
<iframe ng-src="{{url}}" width="300" height="200"></iframe>_x000D_
<br>_x000D_
<button ng-click="changeIt()">Change it</button>_x000D_
</div>
_x000D_
You can catch that exception and return whatever you want from there.
open(target, 'a').close()
scores = {};
try:
with open(target, "rb") as file:
unpickler = pickle.Unpickler(file);
scores = unpickler.load();
if not isinstance(scores, dict):
scores = {};
except EOFError:
return {}
In swift language we can set content mode of UIImage view like following as:
let newImgThumb = UIImageView(frame: CGRect(x: 10, y: 10, width: 100, height: 100))
newImgThumb.contentMode = .scaleAspectFit
You can use this:
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
// Actions to do after 10 seconds
}
}, 10000);
For Stop the Handler, You can try this:
handler.removeCallbacksAndMessages(null);
As you have to use WITH (NOLOCK) for each table it might be annoying to write it in every FROM or JOIN clause. However it has a reason why it is called a "dirty" read. So you really should know when you do one, and not set it as default for the session scope. Why?
Forgetting a WITH (NOLOCK) might not affect your program in a very dramatic way, however doing a dirty read where you do not want one can make the difference in certain circumstances.
So use WITH (NOLOCK) if the current data selected is allowed to be incorrect, as it might be rolled back later. This is mostly used when you want to increase performance, and the requirements on your application context allow it to take the risk that inconsistent data is being displayed. However you or someone in charge has to weigh up pros and cons of the decision of using WITH (NOLOCK).
In Netbeans 8.2
1. Dowload the binaries from the web source. The Apache Commos are in: [http://commons.apache.org/components.html][1] In this case, you must select the "Logging" in the Components menu and follow the link to downloads in the Releases part. Direct URL: [http://commons.apache.org/proper/commons-logging/download_logging.cgi][2] For me, the correct download was the file: commons-logging-1.2-bin.zip from the Binaries.
2. Unzip downloaded content. Now, you can see several jar files inside the directory created from the zip file.
3. Add the library to the project. Right click in the project, select Properties and click in Libraries (in the left side). Click the button "Add Jar/Folder". Go to the previously unzipped contents and select the properly jar file. Clic in "Open" and click in"Ok". The library has been loaded!
I was working on this today for a data.frame (really a data.table) with millions of observations and 35 columns. My goal was to return a list of data.frames (data.tables) each with a single row. That is, I wanted to split each row into a separate data.frame and store these in a list.
Here are two methods I came up with that were roughly 3 times faster than split(dat, seq_len(nrow(dat)))
for that data set. Below, I benchmark the three methods on a 7500 row, 5 column data set (iris repeated 50 times).
library(data.table)
library(microbenchmark)
microbenchmark(
split={dat1 <- split(dat, seq_len(nrow(dat)))},
setDF={dat2 <- lapply(seq_len(nrow(dat)),
function(i) setDF(lapply(dat, "[", i)))},
attrDT={dat3 <- lapply(seq_len(nrow(dat)),
function(i) {
tmp <- lapply(dat, "[", i)
attr(tmp, "class") <- c("data.table", "data.frame")
setDF(tmp)
})},
datList = {datL <- lapply(seq_len(nrow(dat)),
function(i) lapply(dat, "[", i))},
times=20
)
This returns
Unit: milliseconds
expr min lq mean median uq max neval
split 861.8126 889.1849 973.5294 943.2288 1041.7206 1250.6150 20
setDF 459.0577 466.3432 511.2656 482.1943 500.6958 750.6635 20
attrDT 399.1999 409.6316 461.6454 422.5436 490.5620 717.6355 20
datList 192.1175 201.9896 241.4726 208.4535 246.4299 411.2097 20
While the differences are not as large as in my previous test, the straight setDF
method is significantly faster at all levels of the distribution of runs with max(setDF) < min(split) and the attr
method is typically more than twice as fast.
A fourth method is the extreme champion, which is a simple nested lapply
, returning a nested list. This method exemplifies the cost of constructing a data.frame from a list. Moreover, all methods I tried with the data.frame
function were roughly an order of magnitude slower than the data.table
techniques.
data
dat <- vector("list", 50)
for(i in 1:50) dat[[i]] <- iris
dat <- setDF(rbindlist(dat))
Write-Error is for non-terminating errors and throw is for terminating errors
The Write-Error cmdlet declares a non-terminating error. By default, errors are sent in the error stream to the host program to be displayed, along with output.
Non-terminating errors write an error to the error stream, but they do not stop command processing. If a non-terminating error is declared on one item in a collection of input items, the command continues to process the other items in the collection.
To declare a terminating error, use the Throw keyword. For more information, see about_Throw (http://go.microsoft.com/fwlink/?LinkID=145153).
First do a:
git remote rm origin
then
git remote add origin https://github.com/your_user/your_app.git
and voila! Worked for me!
For me i made the fallowing as a test.
string_1="abcd"
def test(string_1):
i = 0
p = ""
x = len(string_1)
while i < x:
y = (string_1)[i]
i=i+1
s = chr(ord(y) + 1)
p=p+s
print(p)
test(string_1)
Not exactly. The h1.hc-reform > p
means "any p
exactly one level underneath h1.hc-reform
".
What you want is h1.hc-reform + p
. Of course, that might cause some issues in older versions of Internet Explorer; if you want to make the page compatible with older IEs, you'll be stuck with either adding a class manually to the paragraphs or using some JavaScript (in jQuery, for example, you could do something like $('h1.hc-reform').next('p').addClass('first-paragraph')
).
More info: http://www.w3.org/TR/CSS2/selector.html or http://css-tricks.com/child-and-sibling-selectors/
The non-greedy regex modifiers are like their greedy counter-parts but with a ?
immediately following them:
* - zero or more
*? - zero or more (non-greedy)
+ - one or more
+? - one or more (non-greedy)
? - zero or one
?? - zero or one (non-greedy)
I was looking for a way to sample a few members of the GroupBy obj - had to address the posted question to get this done.
some_key
columngrouped = df.groupby('some_key')
sampled_df_i = random.sample(grouped.indices, N)
df_list = map(lambda df_i: grouped.get_group(df_i), sampled_df_i)
sampled_df = pd.concat(df_list, axis=0, join='outer')
Go to "Window -> preferences -> Server -> Runtime Environments"
Remove the existing servers they might not have downloaded completely.
Add new Server
Just a little modification to @Epsicron 's answer
SELECT SUBSTRING(string, PATINDEX('%[0-9]%', string), PATINDEX('%[0-9][^0-9]%', string + 't') - PATINDEX('%[0-9]%',
string) + 1) AS Number
FROM (values ('003Preliminary Examination Plan'),
('Coordination005'),
('Balance1000sheet')) as a(string)
no need for a temporary variable
I answer lately and I really recommand you to use SDKMAN instead of Homebrew.
With SDKMAN you can install easily different version of JAVA in your mac and switch from on version to another.
You can also use SDKMAN for ANT, GRADLE, KOTLIN, MAVEN, SCALA, etc...
To install a version in your mac you can run the command sdk install java 15.0.0.j9-adpt
To answer a more generic case, this error is noticed when you pick a function name which is already used in some built in library. For e.g., select.
A simple method to know about it is while compiling the file, the compiler will indicate the previous declaration.
With Scanner the default delimiters are the whitespace characters.
But Scanner can define where a token starts and ends based on a set of delimiter, wich could be specified in two ways:
So useDelimiter()
methods are used to tokenize the Scanner input, and behave like StringTokenizer class, take a look at these tutorials for further information:
And here is an Example:
public static void main(String[] args) {
// Initialize Scanner object
Scanner scan = new Scanner("Anna Mills/Female/18");
// initialize the string delimiter
scan.useDelimiter("/");
// Printing the tokenized Strings
while(scan.hasNext()){
System.out.println(scan.next());
}
// closing the scanner stream
scan.close();
}
Prints this output:
Anna Mills
Female
18
There's also a MediaType
class in androidannotations in case you want to use with android! See here.
Follow below steps to login to your ubuntu VM running in virtual box from the host machine using putty (Without port forwarding):
On Virtualbox manager select the vm, click on settings icon. Then go Networks and enable two adaptors as below:
Start the ubuntu vm.
Edit the file '/etc/network/interfaces' as below and save it:
auto lo
iface lo inet loopback
auto eth0
iface eth0 inet dhcp
auto eth1
iface eth1 inet dhcp
Restart the VM.
Login to the VM and run below command to check the IP allocated to eth1:
ifconfig
Use this IP to open putty session for the VM.
The initialize
method is called after all @FXML
annotated members have been injected. Suppose you have a table view you want to populate with data:
class MyController {
@FXML
TableView<MyModel> tableView;
public MyController() {
tableView.getItems().addAll(getDataFromSource()); // results in NullPointerException, as tableView is null at this point.
}
@FXML
public void initialize() {
tableView.getItems().addAll(getDataFromSource()); // Perfectly Ok here, as FXMLLoader already populated all @FXML annotated members.
}
}
You can update the value like following
auto itr = m.find('ch');
if (itr != m.end()){
(*itr).second = 98;
}
please use some or every instances of ForEach,
Array.prototype.some:
some is much the same as forEach but it break when the callback returns true
Array.prototype.every:
every is almost identical to some except it's expecting false to break the loop.
Example for some:
var ary = ["JavaScript", "Java", "CoffeeScript", "TypeScript"];
ary.some(function (value, index, _ary) {
console.log(index + ": " + value);
return value === "JavaScript";
});
Example for every:
var ary = ["JavaScript", "Java", "CoffeeScript", "TypeScript"];
ary.every(function(value, index, _ary) {
console.log(index + ": " + value);
return value.indexOf("Script") > -1;
});
Find more information
http://www.jsnoob.com/2013/11/26/how-to-break-the-foreach/
There is an example in the launcher app of Android (that I've made a library out of it, here), inside the class that handles wallpapers-picking ("WallpaperPickerActivity") .
The example shows that you need to set a customized theme for this to work. Sadly, this worked for me only using the normal framework, and not the one of the support library.
Here're the themes:
styles.xml
<style name="Theme.WallpaperPicker" parent="Theme.WallpaperCropper">
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:colorBackgroundCacheHint">@null</item>
<item name="android:windowShowWallpaper">true</item>
</style>
<style name="Theme.WallpaperCropper" parent="@android:style/Theme.DeviceDefault">
<item name="android:actionBarStyle">@style/WallpaperCropperActionBar</item>
<item name="android:windowFullscreen">true</item>
<item name="android:windowActionBarOverlay">true</item>
</style>
<style name="WallpaperCropperActionBar" parent="@android:style/Widget.DeviceDefault.ActionBar">
<item name="android:displayOptions">showCustom</item>
<item name="android:background">#88000000</item>
</style>
value-v19/styles.xml
<style name="Theme.WallpaperCropper" parent="@android:style/Theme.DeviceDefault">
<item name="android:actionBarStyle">@style/WallpaperCropperActionBar</item>
<item name="android:windowFullscreen">true</item>
<item name="android:windowActionBarOverlay">true</item>
<item name="android:windowTranslucentNavigation">true</item>
</style>
<style name="Theme" parent="@android:style/Theme.DeviceDefault.Wallpaper.NoTitleBar">
<item name="android:windowTranslucentStatus">true</item>
<item name="android:windowTranslucentNavigation">true</item>
</style>
EDIT: there is a better way to do it, which works on the support library too. Just add this line of code instead of what I've written above:
getSupportActionBar().setDisplayShowCustomEnabled(true);
Using React.createRef()
class MessageBox extends Component {
constructor(props) {
super(props)
this.boxRef = React.createRef()
}
scrollToBottom = () => {
this.boxRef.current.scrollTop = this.boxRef.current.scrollHeight
}
componentDidUpdate = () => {
this.scrollToBottom()
}
render() {
return (
<div ref={this.boxRef}></div>
)
}
}
If you don't have avahi installed then it's probably cups.
Adding to the above. You use the Dispatch timer if you want the tick events marshalled back to the UI thread. Otherwise I would use System.Timers.Timer.
If you are on Docker...
Inside php-container RUN:
#docker-php-ext-install mysqli
#apachectl restart
textarea.addEventListener("keypress", textareaLengthCheck(textarea), false);
You are calling textareaLengthCheck
and then assigning its return value to the event listener. This is why it doesn't update or do anything after loading. Try this:
textarea.addEventListener("keypress",textareaLengthCheck,false);
Aside from that:
var length = textarea.length;
textarea
is the actual textarea, not the value. Try this instead:
var length = textarea.value.length;
Combined with the previous suggestion, your function should be:
function textareaLengthCheck() {
var length = this.value.length;
// rest of code
};
Both
-Djavax.net.ssl.trustStore=path/to/trustStore.jks
and
System.setProperty("javax.net.ssl.trustStore", "cacerts.jks");
do the same thing and have no difference working wise. In your case you just have a typo. You have misspelled trustStore
in javax.net.ssl.trustStore.
I disagree that you should be calling a method on your controller. You should be using a service for any actual functionality, and you should be defining directives for any functionality for scalability and modularity, as well as assigning a click event which contains a call to the service which you inject into your directive.
So, for instance, on your HTML...
<a class="btn" ng-remove-birthday="$index">Delete</a>
Then, create a directive...
angular.module('myApp').directive('ngRemoveBirthday', ['myService', function(myService){
return function(scope, element, attrs){
angular.element(element.bind('click', function(){
myService.removeBirthday(scope.$eval(attrs.ngRemoveBirthday), scope);
};
};
}])
Then in your service...
angular.module('myApp').factory('myService', [function(){
return {
removeBirthday: function(birthdayIndex, scope){
scope.bdays.splice(birthdayIndex);
scope.$apply();
}
};
}]);
When you write your code properly like this, you will make it very easy to write future changes without having to restructure your code. It's organized properly, and you're handling custom click events correctly by binding using custom directives.
For instance, if your client says, "hey, now let's make it call the server and make bread, and then popup a modal." You will be able to easily just go to the service itself without having to add or change any of the HTML, and/or controller method code. If you had just the one line on the controller, you'd eventually need to use a service, for extending the functionality to the heavier lifting the client is asking for.
Also, if you need another 'Delete' button elsewhere, you now have a directive attribute ('ng-remove-birthday') you can easily assign to any element on the page. This now makes it modular and reusable. This will come in handy when dealing with the HEAVY web components paradigm of Angular 2.0. There IS no controller in 2.0. :)
Happy Developing!!!
NullPointerException
s are among the easier exceptions to diagnose, frequently. Whenever you get an exception in Java and you see the stack trace ( that's what your second quote-block is called, by the way ), you read from top to bottom. Often, you will see exceptions that start in Java library code or in native implementations methods, for diagnosis you can just skip past those until you see a code file that you wrote.
Then you like at the line indicated and look at each of the objects ( instantiated classes ) on that line -- one of them was not created and you tried to use it. You can start by looking up in your code to see if you called the constructor on that object. If you didn't, then that's your problem, you need to instantiate that object by calling new Classname( arguments ). Another frequent cause of NullPointerException
s is accidentally declaring an object with local scope when there is an instance variable with the same name.
In your case, the exception occurred in your constructor for Workshop on line 75. <init>
means the constructor for a class. If you look on that line in your code, you'll see the line
denimjeansButton.addItemListener(this);
There are fairly clearly two objects on this line: denimjeansButton
and this
. this
is synonymous with the class instance you are currently in and you're in the constructor, so it can't be this
. denimjeansButton
is your culprit. You never instantiated that object. Either remove the reference to the instance variable denimjeansButton
or instantiate it.
You need to manually download the apt deb package. Then run dpkg and it should install.
You can declare it yourself quite easily:
interface StringConstructor {
format: (formatString: string, ...replacement: any[]) => string;
}
String.format('','');
This is assuming that String.format is defined elsewhere. e.g. in Microsoft Ajax Toolkit : http://www.asp.net/ajaxlibrary/Reference.String-format-Function.ashx
You have to name your struct like that:
typedef struct car_t {
char
wheel_t
} car_t;
I agree with "codehugger" and using the instruction of "orkoden" it worked for me - on NetBeans 7.3 - when you right-click on the file and select context menu - push - a 'push to remote' window opened - there are two options here:
origin:https://github.com/myaccount/myproject.git/
https://github.com/myaccount/myproject.git/
As you can see, the difference is the origin parameter in the URL - you do not want to choose this option (1) you want to check option (2), and that works just fine for me.
If you have server side rendering, you should be careful not to run the code using windows
on the server, where that variable doesn't exist. It would result in code breaking.
export class AppComponent implements OnInit {
routerSubscription: Subscription;
constructor(private router: Router,
@Inject(PLATFORM_ID) private platformId: any) {}
ngOnInit() {
if (isPlatformBrowser(this.platformId)) {
this.routerSubscription = this.router.events
.filter(event => event instanceof NavigationEnd)
.subscribe(event => {
window.scrollTo(0, 0);
});
}
}
ngOnDestroy() {
this.routerSubscription.unsubscribe();
}
}
isPlatformBrowser
is a function used to check if the current platform where the app is rendered is a browser or not. We give it the injected platformId
.
It it also possible to check for existence of variable windows
, to be safe, like this:
if (typeof window != 'undefined')
You get into a difficult situation when it is necessary to understand how scopes, ngRepeat and ngModel with NgModelController work. Also try to use 1.0.3 version. Your example will work a little differently.
You can simply use solution provided by jm-
But if you want to deal with the situation more deeply, you have to understand:
How your example "Binding to each element directly" works for AngularJS 1.0.3:
'f'
into input;ngModelController
changes model for item scope (names array is not changed) => name == 'Samf'
, names == ['Sam', 'Harry', 'Sally']
;$digest
loop is started;ngRepeat
replaces model value from item scope ('Samf'
) by value from unchanged names array ('Sam'
);ngModelController
rerenders input with actual model value ('Sam'
).How your example "Indexing into the array" works:
'f'
into input;ngModelController
changes item in names array
=> `names == ['Samf', 'Harry', 'Sally'];ngRepeat
can't find 'Samf'
in cache;ngRepeat
creates new scope, adds new div element with new input (that is why the input field loses focus - old div with old input is replaced by new div with new input);Also, you can try to use AngularJS Batarang and see how changes $id of the scope of div with input in which you enter.
I came across this question while Googling for "git remove folder from tracking". The OP's question lead me to the answer. I am summarizing it here for future generations.
Question
How do I remove a folder from my git repository without deleting it from my local machine (i.e., development environment)?
Answer
Step 1. Add the folder path to your repo's root .gitignore
file.
path_to_your_folder/
Step 2. Remove the folder from your local git tracking, but keep it on your disk.
git rm -r --cached path_to_your_folder/
Step 3. Push your changes to your git repo.
The folder will be considered "deleted" from Git's point of view (i.e. they are in past history, but not in the latest commit, and people pulling from this repo will get the files removed from their trees), but stay on your working directory because you've used --cached
.
Teradata table or view stores NULL as "?" and SQL considers it as a character or string. This is the main reason for the error "The value violated the integrity constraints for the column." when data is ported from Teradata source to SQL destination. Solution 1: Allow the destination table to hold NULL Solution 2: Convert the '?' character to be stored as some value in the destination table.
So i just found a solution for that: In the hover animation do this:
animation: hover 1s infinite alternate ease-in-out,splash 1;
Take a look at this forum http://htmlcoderhelper.com/why-is-using-a-wild-card-with-a-java-import-statement-bad/. Theres a discussion on how using wildcards can lead to conflicts if you add new classes to the packages and if there are two classes with the same name in different packages where only one of them will be imported.
List<Integer> i = new ArrayList<Integer>(Arrays.asList(0,1,2,3,4,5,6,7,8,9,10));
List<Integer> j = new ArrayList<Integer>();
You need to specify the type for array list or the compiler will give that warning because it cannot identify that you are using the list in a type safe way.
After adding dependencies open "Gradle" ('View'->Tool Windows->Gradle) tab and hit "refresh"
example of adding (compile 'io.reactivex:rxjava:1.1.0'):
If Idea still can not resolve dependency, hence it is possibly the dependency is not in mavenCentral() repository and you need add repository where this dependency located into repositories{}
Another solutions (works with TCPDF)
Use HEREDOC for a long string. Put HERDOC for a CONST for example (define different languages)
$_prepare_const_EN = <<<EOT
this is a long string
and new line as well ...
EOT;
$define('STR_EN', $_prepare_const_EN);
$pdf->InsertText(STR_EN);
works for me wery well....
Found a great solution here http://ajax911.com/numbers-numeric-field-jquery/
I just changed the "keyup" to "keydown" as per my requirement
And if you want Generate a Black Shadow in the background, you can use the following:
background:linear-gradient( rgba(0, 0, 0, 0.5) 100%, rgba(0, 0, 0, 0.5)100%),url("logo/header-background.png");
Update:
Planned in the scope of 3.7 release
https://github.com/microsoft/TypeScript/issues/33352
You can try to write a custom function like that.
The main advantage of the approach is a type-checking and partial intellisense.
export function nullSafe<T,
K0 extends keyof T,
K1 extends keyof T[K0],
K2 extends keyof T[K0][K1],
K3 extends keyof T[K0][K1][K2],
K4 extends keyof T[K0][K1][K2][K3],
K5 extends keyof T[K0][K1][K2][K3][K4]>
(obj: T, k0: K0, k1?: K1, k2?: K2, k3?: K3, k4?: K4, k5?: K5) {
let result: any = obj;
const keysCount = arguments.length - 1;
for (var i = 1; i <= keysCount; i++) {
if (result === null || result === undefined) return result;
result = result[arguments[i]];
}
return result;
}
And usage (supports up to 5 parameters and can be extended):
nullSafe(a, 'b', 'c');
Example on playground.
To use Objectid method you don't need to import it. It is already on the mongodb object.
var ObjectId = new db.ObjectId('58c85d1b7932a14c7a0a320d');_x000D_
db.yourCollection.findOne({ _id: ObjectId }, function (err, info) {_x000D_
console.log(info)_x000D_
});_x000D_
_x000D_
The correct syntax ( as tested in VS 2008 SP1), is this:
public static class ErrorCode
{
public static IDictionary<string, string> ErrorCodeDic;
static ErrorCode()
{
ErrorCodeDic = new Dictionary<string, string>()
{ {"1", "User name or password problem"} };
}
}
I've found the following "pattern" to be very useful:
MainCtrl.$inject = ['$scope', '$rootScope', '$location', 'socket', ...];
function MainCtrl (scope, rootscope, location, thesocket, ...) {
where, MainCtrl is a controller. I am uncomfortable relying on the parameter names of the Controller function doing a one-for-one mimic of the instances for fear that I might change names and muck things up. I much prefer explicitly using $inject for this purpose.
An alternative to numpy.correlate is available in statsmodels.tsa.stattools.acf(). This yields a continuously decreasing autocorrelation function like the one described by OP. Implementing it is fairly simple:
from statsmodels.tsa import stattools
# x = 1-D array
# Yield normalized autocorrelation function of number lags
autocorr = stattools.acf( x )
# Get autocorrelation coefficient at lag = 1
autocorr_coeff = autocorr[1]
The default behavior is to stop at 40 nlags, but this can be adjusted with the nlag=
option for your specific application. There is a citation at the bottom of the page for the statistics behind the function.
Use this link.on Microsoft Support
I gave permission to IUSR_MachineName user on oracle home folder and I was able to resolve the problem
I ended up using GitKraken . I've installed, auth and connected to my repo in 30 seconds.
This question has been pretty well answered, but I'm taking the liberty of adding a javascript solution. Just give the element that you want to 'expand' the id footerspacerdiv
, and this javascript snippet will expand that div until the page takes up the full height of the browser window.
It works based on the observation that, when a page is less than the full height of the browser window, document.body.scrollHeight is equal to document.body.clientHeight. The while loop increases the height of footerspacerdiv
until document.body.scrollHeight is greater than document.body.clientHeight. At this point, footerspacerdiv
will actually be 1 pixel too tall, and the browser will show a vertical scroll bar. So, the last line of the script reduces the height of footerspacerdiv
by one pixel to make the page height exactly the height of the browser window.
By placing footerspacerdiv
just above the 'footer' of the page, this script can be used to 'push the footer down' to the bottom of the page, so that on short pages, the footer is flush with the bottom of the browser window.
<script>
//expand footerspacer div so that footer goes to bottom of page on short pages
var objSpacerDiv=document.getElementById('footerspacer');
var bresize=0;
while(document.body.scrollHeight<=document.body.clientHeight) {
objSpacerDiv.style.height=(objSpacerDiv.clientHeight+1)+"px";
bresize=1;
}
if(bresize) { objSpacerDiv.style.height=(objSpacerDiv.clientHeight-1)+"px"; }
</script>
I'm afraid the DateTimePicker control doesn't have the ability to do those things. It's a pretty basic (and frustrating!) control. Your best option may be to find a third-party control that does what you want.
For the option of typing the date and time manually, you could build a custom component with a TextBox/DateTimePicker combination to accomplish this, and it might work reasonably well, if third-party controls are not an option.
The various directive functions are executed from within two other angular functions called $compile
(where the directive's compile
is executed) and an internal function called nodeLinkFn
(where the directive's controller
, preLink
and postLink
are executed). Various things happen within the angular function before and after the directive functions are called. Perhaps most notably is the child recursion. The following simplified illustration shows key steps within the compile and link phases:
To demonstrate the these steps, let's use the following HTML markup:
<div ng-repeat="i in [0,1,2]">
<my-element>
<div>Inner content</div>
</my-element>
</div>
With the following directive:
myApp.directive( 'myElement', function() {
return {
restrict: 'EA',
transclude: true,
template: '<div>{{label}}<div ng-transclude></div></div>'
}
});
The compile
API looks like so:
compile: function compile( tElement, tAttributes ) { ... }
Often the parameters are prefixed with t
to signify the elements and attributes provided are those of the source template, rather than that of the instance.
Prior to the call to compile
transcluded content (if any) is removed, and the template is applied to the markup. Thus, the element provided to the compile
function will look like so:
<my-element>
<div>
"{{label}}"
<div ng-transclude></div>
</div>
</my-element>
Notice that the transcluded content is not re-inserted at this point.
Following the call to the directive's .compile
, Angular will traverse all child elements, including those that may have just been introduced by the directive (the template elements, for instance).
In our case, three instances of the source template above will be created (by ng-repeat
). Thus, the following sequence will execute three times, once per instance.
The controller
API involves:
controller: function( $scope, $element, $attrs, $transclude ) { ... }
Entering the link phase, the link function returned via $compile
is now provided with a scope.
First, the link function create a child scope (scope: true
) or an isolated scope (scope: {...}
) if requested.
The controller is then executed, provided with the scope of the instance element.
The pre-link
API looks like so:
function preLink( scope, element, attributes, controller ) { ... }
Virtually nothing happens between the call to the directive's .controller
and the .preLink
function. Angular still provide recommendation as to how each should be used.
Following the .preLink
call, the link function will traverse each child element - calling the correct link function and attaching to it the current scope (which serves as the parent scope for child elements).
The post-link
API is similar to that of the pre-link
function:
function postLink( scope, element, attributes, controller ) { ... }
Perhaps worth noticing that once a directive's .postLink
function is called, the link process of all its children elements has completed, including all the children's .postLink
functions.
This means that by the time .postLink
is called, the children are 'live' are ready. This includes:
The template at this stage will thus look like so:
<my-element>
<div class="ng-binding">
"{{label}}"
<div ng-transclude>
<div class="ng-scope">Inner content</div>
</div>
</div>
</my-element>
If you're using gcc and want to disable the warning for selected code, you can use the #pragma compiler directive:
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-variable"
( your problematic library includes )
#pragma GCC diagnostic pop
For code you control, you may also use __attribute__((unused))
to instruct the compiler that specific variables are not used.
private void mainForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (MessageBox.Show("This will close down the whole application. Confirm?", "Close Application", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
MessageBox.Show("The application has been closed successfully.", "Application Closed!", MessageBoxButtons.OK);
System.Windows.Forms.Application.Exit();
}
else
{
this.Activate();
}
}
In the PHP version you can send 'true' in the last parameter, but the default is 'false'. The following algorithm is equivalent to the default PHP's hash function when passing 'sha256' as the first parameter:
public static string GetSha256FromString(string strData)
{
var message = Encoding.ASCII.GetBytes(strData);
SHA256Managed hashString = new SHA256Managed();
string hex = "";
var hashValue = hashString.ComputeHash(message);
foreach (byte x in hashValue)
{
hex += String.Format("{0:x2}", x);
}
return hex;
}
stop all wamp services , exit from wamp.
open notepad then type> SET PASSWORD FOR 'root'@'localhost' = PASSWORD('');
then save it to c: drive with any name .. like this "c:/example.txt"
now goto your "wamp" falder wamp > bin > mysql > mysql(your version) > bin in my case path is "C:\wamp\bin\mysql\mysql5.6.17\bin"
now copy your path then run cmd with (ctrl + r) then type "cmd" (enter)
type cd then right click on cmd and paste path (enter) now type (mysqld --init-file=C:\example.txt) without braces then (enter)
then restart PC or open taskmgr and kill mysqld.exe
start wamp and your password will be removed...
before PHP 5.3
session_register("name");
since PHP 5.3
$_SESSION['name'] = $name;
immutable means you can't not change the value of the same referance.every time you required to create new referance means new memory location. ex:
String str="abc";
str="bcd";
here, in the above code ,in the memory there are 2 blocks for storing the value.the first for value "abc" and second for "bcd".the second value is not replace to first value.
this is call the immutable.
NSString *str = (NSString *)CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)yourString,
NULL,
CFSTR("/:"),
kCFStringEncodingUTF8);
You will need to release or autorelease str
yourself.
From this post:
Default template arguments are not part of the signature of a template
But one can do something like this:
#include <iostream>
struct Foo {
template < class T,
class std::enable_if < !std::is_integral<T>::value, int >::type = 0 >
void f(const T& value)
{
std::cout << "Not int" << std::endl;
}
template<class T,
class std::enable_if<std::is_integral<T>::value, int>::type = 0>
void f(const T& value)
{
std::cout << "Int" << std::endl;
}
};
int main()
{
Foo foo;
foo.f(1);
foo.f(1.1);
// Output:
// Int
// Not int
}
Had same issue in win64bit and JVM 64bit
Was solved by uploading dll to system32
This is all you need: http://api.jquery.com/click/
Having an "else" doesn't apply in this scenario, else would mean "did not click", in which case you just wouldn't do anything.
Ancient topic, if someone still stumbles over this--another workaround is to convert via .astype(str) to string before grouping. That will conserve the NaN's.
df = pd.DataFrame({'a': ['1', '2', '3'], 'b': ['4', np.NaN, '6']})
df['b'] = df['b'].astype(str)
df.groupby(['b']).sum()
a
b
4 1
6 3
nan 2
You mention C# in your question so it may help to think of as XSD as serving a similar role to a C# interface.
It defines what the XML should 'look like' in a similar way that an interface defines what a class should implement.
I needed to import javaee-api as well.
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
</dependency>
Unless I got following error:
package javax.servlet.http does not exist
javax.servlet.annotation does not exist
javax.servlet.http does not exist
...
Since this question was originally asked, John Resig (the primary author of jQuery) has forked and improved the js-hotkeys project. His version is available at:
I haven't tested on other Laravel versions but on 5.3-5.8 you reference the query parameter as if it were a member of the Request
class
.
http://example.com/path?page=2
Route::get('/path', function(Request $request){
dd($request->page);
});
//or in your controller
public function foo(Request $request){
dd($request->page);
}
//NOTE: If you are wondering where the request instance is coming from, Laravel automatically injects the request instance from the IOC container
//output
"2"
We can also pass in a default value which is returned if a parameter doesn't exist. It's much cleaner than a ternary expression that you'd normally use with the request globals
//wrong way to do it in Laravel
$page = isset($_POST['page']) ? $_POST['page'] : 1;
//do this instead
$request->get('page', 1);
//returns page 1 if there is no page
//NOTE: This behaves like $_REQUEST array. It looks in both the
//request body and the query string
$request->input('page', 1);
$page = request('page', 1);
//returns page 1 if there is no page parameter in the query string
//it is the equivalent of
$page = 1;
if(!empty($_GET['page'])
$page = $_GET['page'];
The default parameter is optional therefore one can omit it
While the input method retrieves values from entire request payload (including the query string), the query method will only retrieve values from the query string
//this is the equivalent of retrieving the parameter
//from the $_GET global array
$page = $request->query('page');
//with a default
$page = $request->query('page', 1);
$page = Request::get('page');
//with a default value
$page = Request::get('page', 1);
You can read more in the official documentation https://laravel.com/docs/5.8/requests
If this webserver is only for testing and demoing purposes. You can use ngrok, a open source too that tunnels your http traffic.
Bascially ngrok creates a public URL (both http and https) and then tunnels the traffic to whatever port your Flask process is running on.
It only takes a couple minutes to set up. You first have to download the software. Then run the command
./ngrok http [port number your python process is running on]
It will then open up a window in terminal giving you both an http and https url to access your web app.
Please remember that Google also use reCaptcha together with
Canvas fingerprinting
to uniquely recognize User/Browsers without cookies!
Since you are new to Android development you may not know about Content Providers, which are database abstractions. They may not be the right thing for your project, but you should check them out: http://developer.android.com/guide/topics/providers/content-providers.html
List<int>[] a = new List<int>[100];
You still would have to allocate each individual list in the array before you can use it though:
for (int i = 0; i < a.Length; i++)
a[i] = new List<int>();
In python a list knows its length, so you can just do len(sys.argv)
to get the number of elements in argv
.
I resolved the same issue by adding this property to hdfs-site.xml
<property>
<name>fs.default.name</name>
<value>hdfs://localhost:9000</value>
</property>
you can wrap the content of the <tbody>
in a scrollable <div>
:
html
....
<tbody>
<tr>
<td colspan="2">
<div class="scrollit">
<table>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
...
css
.scrollit {
overflow:scroll;
height:100px;
}
see my jsfiddle, forked from yours: http://jsfiddle.net/VTNax/2/
I use this code, and it works for me:
DataRowView typeItem = (DataRowView)myComboBox.SelectedItem;
string value = typeItem.Row[0].ToString();
Add checked to both of your radio button. And then show/hide your desired one on document ready.
<div class="form-group">
<div class="mt-radio-inline" style="padding-left:15px;">
<label class="mt-radio mt-radio-outline">
Full Edition
<input type="radio" value="@((int)SelectEditionTypeEnum.FullEdition)" asp-for="SelectEditionType" checked>
<span></span>
</label>
<label class="mt-radio mt-radio-outline">
Select Modules
<input type="radio" value="@((int)SelectEditionTypeEnum.CustomEdition)" asp-for="SelectEditionType" checked>
<span></span>
</label>
</div>
</div>