Use cbind
e.g.
df <- data.frame(b = runif(6), c = rnorm(6))
cbind(a = 0, df)
giving:
> cbind(a = 0, df)
a b c
1 0 0.5437436 -0.1374967
2 0 0.5634469 -1.0777253
3 0 0.9018029 -0.8749269
4 0 0.1649184 -0.4720979
5 0 0.6992595 0.6219001
6 0 0.6907937 -1.7416569
Almost all Oracle deployments are done through SQL*Plus (that weird little command line tool that your DBA uses). And in SQL*Plus a lone slash basically means "re-execute last SQL or PL/SQL command that I just executed".
See
Rule of thumb would be to use slash with things that do BEGIN .. END
or where you can use CREATE OR REPLACE
.
For inserts that need to be unique use
INSERT INTO my_table ()
SELECT <values to be inserted>
FROM dual
WHERE NOT EXISTS (SELECT
FROM my_table
WHERE <identify data that you are trying to insert>)
There are already nice solution has been given. The below code can help others to query over datatable and get the value of each row of the datatable for the ImagePath column.
for (int i = 0; i < dataTable.Rows.Count; i++)
{
var theUrl = dataTable.Rows[i]["ImagePath"].ToString();
}
use fastcopy, a free tool. it has a delete option that is a lot faster then the way windows deletes files.
I find it useful to have a class, derived from threading.Thread
, to encapsulate my thread functionality. You simply provide your own main loop in an overridden version of run()
in this class. Calling start()
arranges for the object’s run()
method to be invoked in a separate thread.
Inside the main loop, periodically check whether a threading.Event
has been set. Such an event is thread-safe.
Inside this class, you have your own join()
method that sets the stop event object before calling the join()
method of the base class. It can optionally take a time value to pass to the base class's join()
method to ensure your thread is terminated in a short amount of time.
import threading
import time
class MyThread(threading.Thread):
def __init__(self, sleep_time=0.1):
self._stop_event = threading.Event()
self._sleep_time = sleep_time
"""call base class constructor"""
super().__init__()
def run(self):
"""main control loop"""
while not self._stop_event.isSet():
#do work
print("hi")
self._stop_event.wait(self._sleep_time)
def join(self, timeout=None):
"""set stop event and join within a given time period"""
self._stop_event.set()
super().join(timeout)
if __name__ == "__main__":
t = MyThread()
t.start()
time.sleep(5)
t.join(1) #wait 1s max
Having a small sleep inside the main loop before checking the threading.Event
is less CPU intensive than looping continuously. You can have a default sleep time (e.g. 0.1s), but you can also pass the value in the constructor.
basename
and dirname
solutions are more convenient. Those are alternative commands:
FILE_PATH="/opt/datastores/sda2/test.old.img"
echo "$FILE_PATH" | sed "s/.*\///"
This returns test.old.img
like basename
.
This is salt filename without extension:
echo "$FILE_PATH" | sed -r "s/.+\/(.+)\..+/\1/"
It returns test.old
.
And following statement gives the full path like dirname
command.
echo "$FILE_PATH" | sed -r "s/(.+)\/.+/\1/"
It returns /opt/datastores/sda2
The method I prefer assigns an array of data to the combobox. Click on the body of your userform and change the "Click" event to "Initialize". Now the combobox will fill upon the initializing of the userform. I hope this helps.
Sub UserForm_Initialize()
ComboBox1.List = Array("1001", "1002", "1003", "1004", "1005", "1006", "1007", "1008", "1009", "1010")
End Sub
The Maven Dependency Plugin will help, especially the dependency:analyze
goal:
dependency:analyze
analyzes the dependencies of this project and determines which are: used and declared; used and undeclared; unused and declared.
Another thing that might help to do some cleanup is the Dependency Convergence report from the Maven Project Info Reports Plugin.
If you need just to execute your VLC playback process and only give control back to your application process when it is done and nothing more complex, then i suppose you can use just:
system("The same thing you type into console");
In CSS, FontAwesome unicode works only when the correct font family is declared (version 4 or less):
font-family: "FontAwesome";
content: "\f066";
Update - Version 5 has different names:
Free
font-family: "Font Awesome 5 Free"
Pro
font-family: "Font Awesome 5 Pro"
Brands
font-family: "Font Awesome 5 Brands"
See this related answer: https://stackoverflow.com/a/48004111/2575724
As per comment (BuddyZ) some more info here https://fontawesome.com/how-to-use/on-the-desktop/setup/getting-started
Project Rebuild solved my problem.
In Android studio in the toolbar.. Build>Rebuild Project.
For me this was the best solution:
HTML:
<div id="outer">
<img src="logo.png">
</div>
CSS:
#outer {
position: fixed;
top: 50%;
left: 50%;
/* bring your own prefixes */
transform: translate(-50%, -50%);
}
.cont{_x000D_
height: 100px;_x000D_
overflow-x: hidden;_x000D_
overflow-y: auto;_x000D_
transform: rotate(180deg);_x000D_
direction:rtl;_x000D_
text-align:left;_x000D_
}_x000D_
ul{_x000D_
overflow: hidden;_x000D_
transform: rotate(180deg);_x000D_
}
_x000D_
<div class="cont"> _x000D_
<ul>_x000D_
<li>0</li>_x000D_
<li>1</li>_x000D_
<li>2</li>_x000D_
<li>3</li>_x000D_
<li>4</li>_x000D_
<li>5</li>_x000D_
<li>6</li>_x000D_
<li>7</li>_x000D_
<li>8</li>_x000D_
<li>9</li>_x000D_
<li>10</li> _x000D_
</ul>_x000D_
</div>
_x000D_
Run code snippet
to see the effect. (PS: If Run code snippet
is not working, try this: https://jsfiddle.net/Yeshen/xm2yLksu/3/ )
How it work:
Default overflow is scroll from top to bottom.
transform: rotate(180deg)
can make it scroll or load dynamic block from bottom to top.
Reinstall JDK and set system variable JAVA_HOME on your JDK. (e.g. C:\tools\jdk7)
And add JAVA_HOME variable to your PATH system variable
Type in command line
echo %JAVA_HOME%
and
java -version
To verify whether your installation was done successfully.
This problem generally occurs in Windows when your "Java Runtime Environment" registry entry is missing or mismatched with the installed JDK. The mismatch can be due to multiple JDKs.
Steps to resolve:
Open the Run window:
Press windows+R
Open registry window:
Type regedit
and enter.
Go to: \HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\
If Java Runtime Environment is not present inside JavaSoft, then create a new Key and give the name Java Runtime Environment.
For Java Runtime Environment create "CurrentVersion" String Key and give appropriate version as value:
Create a new subkey of 1.8.
For 1.8 create a String Key with name JavaHome with the value of JRE home:
Ref: https://mybindirectory.blogspot.com/2019/05/error-could-not-find-javadll.html
if somebody wants the answer in swift 3
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
switch application.applicationState {
case .active:
//app is currently active, can update badges count here
break
case .inactive:
//app is transitioning from background to foreground (user taps notification), do what you need when user taps here
break
case .background:
//app is in background, if content-available key of your notification is set to 1, poll to your backend to retrieve data and update your interface here
break
default:
break
}
}
You have to first obtain the Range object. Also, getCell() will not return the value of the cell but instead will return a Range object of the cell. So, use something on the lines of
function email() {
// Opens SS by its ID
var ss = SpreadsheetApp.openById("0AgJjDgtUl5KddE5rR01NSFcxYTRnUHBCQ0stTXNMenc");
// Get the name of this SS
var name = ss.getName(); // Not necessary
// Read cell 1,1 * Line below does't work *
// var data = Range.getCell(0, 0);
var sheet = ss.getSheetByName('Sheet1'); // or whatever is the name of the sheet
var range = sheet.getRange(1,1);
var data = range.getValue();
}
The hierarchy is Spreadsheet --> Sheet --> Range --> Cell.
You can use the dict.fromkeys
class method ...
>>> dict.fromkeys(range(5), True)
{0: True, 1: True, 2: True, 3: True, 4: True}
This is the fastest way to create a dictionary where all the keys map to the same value.
But do not use this with mutable objects:
d = dict.fromkeys(range(5), [])
# {0: [], 1: [], 2: [], 3: [], 4: []}
d[1].append(2)
# {0: [2], 1: [2], 2: [2], 3: [2], 4: [2]} !!!
If you don't actually need to initialize all the keys, a defaultdict
might be useful as well:
from collections import defaultdict
d = defaultdict(True)
To answer the second part, a dict-comprehension is just what you need:
{k: k for k in range(10)}
You probably shouldn't do this but you could also create a subclass of dict
which works somewhat like a defaultdict
if you override __missing__
:
>>> class KeyDict(dict):
... def __missing__(self, key):
... #self[key] = key # Maybe add this also?
... return key
...
>>> d = KeyDict()
>>> d[1]
1
>>> d[2]
2
>>> d[3]
3
>>> print(d)
{}
You can solve this error by running cmd as admin than
Do the same as in picture for windows 32 bit
Just make changes in 64 bit as framework64 instead of framework only
Than go to iis and refresh the site
If u still got some error make changes in application pool
As there is no proper wheel file in http://www.lfd.uci.edu/~gohlke/pythonlibs/#opencv?
Try this:(Worked in Anaconda Prompt or Pycharm)
pip install opencv-contrib-python
pip install opencv-python
Brief syntax lesson
Cells(Row, Column)
identifies a cell. Row must be an integer between 1 and the maximum for version of Excel you are using. Column must be a identifier (for example: "A", "IV", "XFD") or a number (for example: 1, 256, 16384)
.Cells(Row, Column)
identifies a cell within a sheet identified in a earlier With statement:
With ActiveSheet
:
.Cells(Row,Column)
:
End With
If you omit the dot, Cells(Row,Column)
is within the active worksheet. So wsh = ActiveWorkbook
wsh.Range
is not strictly necessary. However, I always use a With statement so I do not wonder which sheet I meant when I return to my code in six months time. So, I would write:
With ActiveSheet
:
.Range.
:
End With
Actually, I would not write the above unless I really did want the code to work on the active sheet. What if the user has the wrong sheet active when they started the macro. I would write:
With Sheets("xxxx")
:
.Range.
:
End With
because my code only works on sheet xxxx.
Cells(Row,Column)
identifies a cell. Cells(Row,Column).xxxx identifies a property of the cell. Value
is a property. Value is the default property so you can usually omit it and the compiler will know what you mean. But in certain situations the compiler can be confused so the advice to include the .Value
is good.
Cells(Row,Column) like "*Miami*"
will give True if the cell is "Miami", "South Miami", "Miami, North" or anything similar.
Cells(Row,Column).Value = "Miami"
will give True if the cell is exactly equal to "Miami". "MIAMI" for example will give False. If you want to accept MIAMI, use the lower case function:
Lcase(Cells(Row,Column).Value) = "miami"
My suggestions
Your sample code keeps changing as you try different suggestions which I find confusing. You were using Cells(Row,Column) <> "Miami"
when I started typing this.
Use
If Cells(i, "A").Value like "*Miami*" And Cells(i, "D").Value like "*Florida*" Then
Cells(i, "C").Value = "BA"
if you want to accept, for example, "South Miami" and "Miami, North".
Use
If Cells(i, "A").Value = "Miami" And Cells(i, "D").Value like "Florida" Then
Cells(i, "C").Value = "BA"
if you want to accept, exactly, "Miami" and "Florida".
Use
If Lcase(Cells(i, "A").Value) = "miami" And _
Lcase(Cells(i, "D").Value) = "florida" Then
Cells(i, "C").Value = "BA"
if you don't care about case.
import { FormControl, FormGroup, AbstractControl, FormBuilder, Validators } from '@angular/forms';_x000D_
_x000D_
_x000D_
this.userInfoForm = new FormGroup({_x000D_
userInfoUserName: new FormControl({ value: '' }, Validators.compose([Validators.required])),_x000D_
userInfoName: new FormControl({ value: '' }, Validators.compose([Validators.required])),_x000D_
userInfoSurName: new FormControl({ value: '' }, Validators.compose([Validators.required]))_x000D_
});
_x000D_
<form [formGroup]="userInfoForm" class="form-horizontal">_x000D_
<div class="form-group">_x000D_
<label class="control-label"><i>*</i> User Name</label>_x000D_
<input type="text" formControlName="userInfoUserName" class="form-control" [(ngModel)]="userInfo.userName">_x000D_
</div>_x000D_
<div class="form-group">_x000D_
<label class="control-label"><i>*</i> Name</label>_x000D_
<input type="text" formControlName="userInfoName" class="form-control" [(ngModel)]="userInfo.name">_x000D_
</div>_x000D_
<div class="form-group">_x000D_
<label class="control-label"><i>*</i> Surname</label>_x000D_
<input type="text" formControlName="userInfoSurName" class="form-control" [(ngModel)]="userInfo.surName">_x000D_
</div>_x000D_
</form>
_x000D_
You can use CSS3 transitions or maybe CSS3 animations to slide in an element.
For browser support: http://caniuse.com/
I made two quick examples just to show you how I mean.
CSS transition (on hover)
Relevant Code
.wrapper:hover #slide {
transition: 1s;
left: 0;
}
In this case, Im just transitioning the position from left: -100px;
to 0;
with a 1s. duration. It's also possible to move the element using transform: translate();
CSS animation
#slide {
position: absolute;
left: -100px;
width: 100px;
height: 100px;
background: blue;
-webkit-animation: slide 0.5s forwards;
-webkit-animation-delay: 2s;
animation: slide 0.5s forwards;
animation-delay: 2s;
}
@-webkit-keyframes slide {
100% { left: 0; }
}
@keyframes slide {
100% { left: 0; }
}
Same principle as above (Demo One), but the animation starts automatically after 2s, and in this case I've set animation-fill-mode
to forwards
, which will persist the end state, keeping the div visible when the animation ends.
Like I said, two quick example to show you how it could be done.
EDIT: For details regarding CSS Animations and Transitions see:
Animations
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_animations
Transitions
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_transitions
Hope this helped.
You can try using a simple library like
After installing via gradle and adding permissions initiate SmsVerifyCatcher in method like onCreate activity:
smsVerifyCatcher = new SmsVerifyCatcher(this, new OnSmsCatchListener<String>() {
@Override
public void onSmsCatch(String message) {
String code = parseCode(message);//Parse verification code
etCode.setText(code);//set code in edit text
//then you can send verification code to server
}
});
Also, override activity lifecicle methods:
@Override
protected void onStart() {
super.onStart();
smsVerifyCatcher.onStart();
}
@Override
protected void onStop() {
super.onStop();
smsVerifyCatcher.onStop();
}
/**
* need for Android 6 real time permissions
*/
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
smsVerifyCatcher.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
public String parseCode(String message) {
Pattern p = Pattern.compile("\\b\\d{4}\\b");
Matcher m = p.matcher(message);
String code = "";
while (m.find()) {
code = m.group(0);
}
return code;
}
Here you go:
JS:
$('form').on('submit', function (e) {
e.preventDefault();
if (!$('#email').val())
$('#email').parent().append('<span class="error">Please enter your email address.</span>');
if(!$('#password').val())
$('#password').parent().append('<span class="error">Please enter your password.</span>');
});
CSS:
@charset "utf-8";
/* CSS Document */
/* ---------- FONTAWESOME ---------- */
/* ---------- http://fortawesome.github.com/Font-Awesome/ ---------- */
/* ---------- http://weloveiconfonts.com/ ---------- */
@import url(http://weloveiconfonts.com/api/?family=fontawesome);
/* ---------- ERIC MEYER'S RESET CSS ---------- */
/* ---------- http://meyerweb.com/eric/tools/css/reset/ ---------- */
@import url(http://meyerweb.com/eric/tools/css/reset/reset.css);
/* ---------- FONTAWESOME ---------- */
[class*="fontawesome-"]:before {
font-family: 'FontAwesome', sans-serif;
}
/* ---------- GENERAL ---------- */
body {
background-color: #C0C0C0;
color: #000;
font-family: "Varela Round", Arial, Helvetica, sans-serif;
font-size: 16px;
line-height: 1.5em;
}
input {
border: none;
font-family: inherit;
font-size: inherit;
font-weight: inherit;
line-height: inherit;
-webkit-appearance: none;
}
/* ---------- LOGIN ---------- */
#login {
margin: 50px auto;
width: 400px;
}
#login h2 {
background-color: #f95252;
-webkit-border-radius: 20px 20px 0 0;
-moz-border-radius: 20px 20px 0 0;
border-radius: 20px 20px 0 0;
color: #fff;
font-size: 28px;
padding: 20px 26px;
}
#login h2 span[class*="fontawesome-"] {
margin-right: 14px;
}
#login fieldset {
background-color: #fff;
-webkit-border-radius: 0 0 20px 20px;
-moz-border-radius: 0 0 20px 20px;
border-radius: 0 0 20px 20px;
padding: 20px 26px;
}
#login fieldset div {
color: #777;
margin-bottom: 14px;
}
#login fieldset p:last-child {
margin-bottom: 0;
}
#login fieldset input {
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
}
#login fieldset .error {
display: block;
color: #FF1000;
font-size: 12px;
}
}
#login fieldset input[type="email"], #login fieldset input[type="password"] {
background-color: #eee;
color: #777;
padding: 4px 10px;
width: 328px;
}
#login fieldset input[type="submit"] {
background-color: #33cc77;
color: #fff;
display: block;
margin: 0 auto;
padding: 4px 0;
width: 100px;
}
#login fieldset input[type="submit"]:hover {
background-color: #28ad63;
}
HTML:
<div id="login">
<h2><span class="fontawesome-lock"></span>Sign In</h2>
<form action="javascript:void(0);" method="POST">
<fieldset>
<div><label for="email">E-mail address</label></div>
<div><input type="email" id="email" /></div>
<div><label for="password">Password</label></div>
<div><input type="password" id="password" /></div> <!-- JS because of IE support; better: placeholder="Email" -->
<div><input type="submit" value="Sign In"></div>
</fieldset>
</form>
And the fiddle: jsfiddle
I'm not sure you really want to do what you say you want to do, but it's not for me to reason why!
You cannot add properties to a class after it has been JITed.
The closest you could get would be to dynamically create a subtype with Reflection.Emit and copy the existing fields over, but you'd have to update all references to the the object yourself.
You also wouldn't be able to access those properties at compile time.
Something like:
public class Dynamic
{
public Dynamic Add<T>(string key, T value)
{
AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("DynamicAssembly"), AssemblyBuilderAccess.Run);
ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("Dynamic.dll");
TypeBuilder typeBuilder = moduleBuilder.DefineType(Guid.NewGuid().ToString());
typeBuilder.SetParent(this.GetType());
PropertyBuilder propertyBuilder = typeBuilder.DefineProperty(key, PropertyAttributes.None, typeof(T), Type.EmptyTypes);
MethodBuilder getMethodBuilder = typeBuilder.DefineMethod("get_" + key, MethodAttributes.Public, CallingConventions.HasThis, typeof(T), Type.EmptyTypes);
ILGenerator getter = getMethodBuilder.GetILGenerator();
getter.Emit(OpCodes.Ldarg_0);
getter.Emit(OpCodes.Ldstr, key);
getter.Emit(OpCodes.Callvirt, typeof(Dynamic).GetMethod("Get", BindingFlags.Instance | BindingFlags.NonPublic).MakeGenericMethod(typeof(T)));
getter.Emit(OpCodes.Ret);
propertyBuilder.SetGetMethod(getMethodBuilder);
Type type = typeBuilder.CreateType();
Dynamic child = (Dynamic)Activator.CreateInstance(type);
child.dictionary = this.dictionary;
dictionary.Add(key, value);
return child;
}
protected T Get<T>(string key)
{
return (T)dictionary[key];
}
private Dictionary<string, object> dictionary = new Dictionary<string,object>();
}
I don't have VS installed on this machine so let me know if there are any massive bugs (well... other than the massive performance problems, but I didn't write the specification!)
Now you can use it:
Dynamic d = new Dynamic();
d = d.Add("MyProperty", 42);
Console.WriteLine(d.GetType().GetProperty("MyProperty").GetValue(d, null));
You could also use it like a normal property in a language that supports late binding (for example, VB.NET)
XML FILE IN VALUES
<style name="tab">
<item name="android:textSize">@dimen/_10ssp</item>
<item name="android:textColor">#FFFFFF</item>
</style>
TAB LAYOUT
<com.google.android.material.tabs.TabLayout
android:layout_width="match_parent"
android:layout_height="@dimen/_27sdp"
android:layout_marginLeft="@dimen/_10sdp"
android:layout_marginRight="@dimen/_10sdp"
app:layout_constraintEnd_toEndOf="parent"
app:tabTextAppearance="@style/tab"
app:tabGravity="fill"
android:layout_marginTop="@dimen/_10sdp"
app:layout_constraintStart_toStartOf="parent"
>
<com.google.android.material.tabs.TabItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TAB 1"
android:scrollbarSize="@dimen/_4sdp"
/>
<com.google.android.material.tabs.TabItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scrollbarSize="@dimen/_6sdp"
android:text="TAB 2" />
<com.google.android.material.tabs.TabItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scrollbarSize="@dimen/_4sdp"
android:text="TAB 3" />
</com.google.android.material.tabs.TabLayout>
This just worked for me:
I was trying to leave a space in the Apple Pages new LaTeX input area. I typed the following and it left a clean line.
\mbox{\phantom{0}}\\
If you need a zero padded difference between 2 dates:
SELECT convert(varchar(2),FORMAT(DATEDIFF(s, @startDate, @endDate)/3600,'0#'))+':'
+convert(varchar(2),FORMAT(DATEDIFF(s, @startDate, @endDate)%3600/60,'0#'))+':'
+convert(varchar(2),FORMAT(DATEDIFF(s, @startDate, @endDate)%60,'0#')) AS Duration
Very simple, no library required:
var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
or you might prefer:
var date = new Date(), y = date.getFullYear(), m = date.getMonth();
var firstDay = new Date(y, m, 1);
var lastDay = new Date(y, m + 1, 0);
Some browsers will treat two digit years as being in the 20th century, so that:
new Date(14, 0, 1);
gives 1 January, 1914. To avoid that, create a Date then set its values using setFullYear:
var date = new Date();
date.setFullYear(14, 0, 1); // 1 January, 14
I came up with the solution and posted it on my blog
here is the htaccess code also
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . / [L,R=301]
but I posted other solutions on my blog too, it depends what you need really
As ams said above, don't take a pointer to a member of a struct that's packed. This is simply playing with fire. When you say __attribute__((__packed__))
or #pragma pack(1)
, what you're really saying is "Hey gcc, I really know what I'm doing." When it turns out that you do not, you can't rightly blame the compiler.
Perhaps we can blame the compiler for it's complacency though. While gcc does have a -Wcast-align
option, it isn't enabled by default nor with -Wall
or -Wextra
. This is apparently due to gcc developers considering this type of code to be a brain-dead "abomination" unworthy of addressing -- understandable disdain, but it doesn't help when an inexperienced programmer bumbles into it.
Consider the following:
struct __attribute__((__packed__)) my_struct {
char c;
int i;
};
struct my_struct a = {'a', 123};
struct my_struct *b = &a;
int c = a.i;
int d = b->i;
int *e __attribute__((aligned(1))) = &a.i;
int *f = &a.i;
Here, the type of a
is a packed struct (as defined above). Similarly, b
is a pointer to a packed struct. The type of of the expression a.i
is (basically) an int l-value with 1 byte alignment. c
and d
are both normal int
s. When reading a.i
, the compiler generates code for unaligned access. When you read b->i
, b
's type still knows it's packed, so no problem their either. e
is a pointer to a one-byte-aligned int, so the compiler knows how to dereference that correctly as well. But when you make the assignment f = &a.i
, you are storing the value of an unaligned int pointer in an aligned int pointer variable -- that's where you went wrong. And I agree, gcc should have this warning enabled by default (not even in -Wall
or -Wextra
).
Another option would be to look at the ro.hardware property and see if its set to goldfish. Unfortunately there doesn't seem to be an easy way to do this from Java but its trivial from C using property_get().
HTML
create div with id='dvFile'
;
create a button
;
onclick
of that button calling function add_more()
JavaScript
function add_more() {
var txt = "<br><input type=\"file\" name=\"item_file[]\">";
document.getElementById("dvFile").innerHTML += txt;
}
PHP
if(count($_FILES["item_file"]['name'])>0)
{
//check if any file uploaded
$GLOBALS['msg'] = ""; //initiate the global message
for($j=0; $j < count($_FILES["item_file"]['name']); $j++)
{ //loop the uploaded file array
$filen = $_FILES["item_file"]['name']["$j"]; //file name
$path = 'uploads/'.$filen; //generate the destination path
if(move_uploaded_file($_FILES["item_file"]['tmp_name']["$j"],$path))
{
//upload the file
$GLOBALS['msg'] .= "File# ".($j+1)." ($filen) uploaded successfully<br>";
//Success message
}
}
}
else {
$GLOBALS['msg'] = "No files found to upload"; //No file upload message
}
In this way you can add file/images, as many as required, and handle them through php script.
You will want to use the String class' Split() method and pass in a regular expression of "\D+" which will match at least one non-number.
myString.split("\\D+");
An interesting alternative to objdump is gdb. You don't have to run the binary or have debuginfo.
$ gdb -q ./a.out
Reading symbols from ./a.out...(no debugging symbols found)...done.
(gdb) info functions
All defined functions:
Non-debugging symbols:
0x00000000004003a8 _init
0x00000000004003e0 __libc_start_main@plt
0x00000000004003f0 __gmon_start__@plt
0x0000000000400400 _start
0x0000000000400430 deregister_tm_clones
0x0000000000400460 register_tm_clones
0x00000000004004a0 __do_global_dtors_aux
0x00000000004004c0 frame_dummy
0x00000000004004f0 fce
0x00000000004004fb main
0x0000000000400510 __libc_csu_init
0x0000000000400580 __libc_csu_fini
0x0000000000400584 _fini
(gdb) disassemble main
Dump of assembler code for function main:
0x00000000004004fb <+0>: push %rbp
0x00000000004004fc <+1>: mov %rsp,%rbp
0x00000000004004ff <+4>: sub $0x10,%rsp
0x0000000000400503 <+8>: callq 0x4004f0 <fce>
0x0000000000400508 <+13>: mov %eax,-0x4(%rbp)
0x000000000040050b <+16>: mov -0x4(%rbp),%eax
0x000000000040050e <+19>: leaveq
0x000000000040050f <+20>: retq
End of assembler dump.
(gdb) disassemble fce
Dump of assembler code for function fce:
0x00000000004004f0 <+0>: push %rbp
0x00000000004004f1 <+1>: mov %rsp,%rbp
0x00000000004004f4 <+4>: mov $0x2a,%eax
0x00000000004004f9 <+9>: pop %rbp
0x00000000004004fa <+10>: retq
End of assembler dump.
(gdb)
With full debugging info it's even better.
(gdb) disassemble /m main
Dump of assembler code for function main:
9 {
0x00000000004004fb <+0>: push %rbp
0x00000000004004fc <+1>: mov %rsp,%rbp
0x00000000004004ff <+4>: sub $0x10,%rsp
10 int x = fce ();
0x0000000000400503 <+8>: callq 0x4004f0 <fce>
0x0000000000400508 <+13>: mov %eax,-0x4(%rbp)
11 return x;
0x000000000040050b <+16>: mov -0x4(%rbp),%eax
12 }
0x000000000040050e <+19>: leaveq
0x000000000040050f <+20>: retq
End of assembler dump.
(gdb)
objdump has a similar option (-S)
The only way in MySQL to do this dynamically is with Prepared statements. Here is a good article about them:
Dynamic pivot tables (transform rows to columns)
Your code would look like this:
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'MAX(IF(pa.fieldname = ''',
fieldname,
''', pa.fieldvalue, NULL)) AS ',
fieldname
)
) INTO @sql
FROM product_additional;
SET @sql = CONCAT('SELECT p.id
, p.name
, p.description, ', @sql, '
FROM product p
LEFT JOIN product_additional AS pa
ON p.id = pa.id
GROUP BY p.id');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
See Demo
NOTE: GROUP_CONCAT function has a limit of 1024 characters. See parameter group_concat_max_len
SELECT field1 FROM table1
UNION
SELECT field1 FROM table2
ORDER BY field1
OpenGL should be present already - it will probably be Freeglut / GLUT that is missing.
GLUT is very dated now and not actively supported - so you should certainly be using Freeglut instead. You won't have to change your code at all, and a few additional features become available.
You'll find pre-packaged sets of files from here: http://freeglut.sourceforge.net/index.php#download If you don't see the "lib" folder, it's because you didn't download the pre-packaged set. "Martin Payne's Windows binaries" is posted at above link and works on Windows 8.1 with Visual Studio 2013 at the time of this writing.
When you download these you'll find that the Freeglut folder has three subfolders: - bin folder: this contains the dll files for runtime - include: the header files for compilation - lib: contains library files for compilation/linking
Installation instructions usually suggest moving these files into the visual studio folder and the Windows system folder: It is best to avoid doing this as it makes your project less portable, and makes it much more difficult if you ever need to change which version of the library you are using (old projects might suddenly stop working, etc.)
Instead (apologies for any inconsistencies, I'm basing these instructions on VS2010)... - put the freeglut folder somewhere else, e.g. C:\dev - Open your project in Visual Studio - Open project properties - There should be a tab for VC++ Directories, here you should add the appropriate include and lib folders, e.g.: C:\dev\freeglut\include and C:\dev\freeglut\lib - (Almost) Final step is to ensure that the opengl lib file is actually linked during compilation. Still in project properties, expand the linker menu, and open the input tab. For Additional Dependencies add opengl32.lib (you would assume that this would be linked automatically just by adding the include GL/gl.h to your project, but for some reason this doesn't seem to be the case)
At this stage your project should compile OK. To actually run it, you also need to copy the freeglut.dll files into your project folder
Try this (but once clicked, it is not reversible):
HTML:
<a id="test"><img src="normal-image.png"/></a>
CSS:
a#test {
border: 0;
}
a#test:visited img, a#test:active img {
background-image: url(clicked-image.png);
}
With mysqli
you're able to use multiple statements for real using mysqli_multi_query()
.
The most commonly used way is using jQuery for this purpose:
var safestring = $('<div>').text(unsafestring).html();
If you want to to encode all the HTML entities you will have to use a library or write it yourself.
You can use a more compact library than jQuery, like HTML Encoder and Decode
There is also another possible source of this error. In some J2EE / web containers (in my experience under Jboss 7.x and Tomcat 7.x) You have to add each class You want to use as a hibernate Entity into the file persistence.xml as
<class>com.yourCompanyName.WhateverEntityClass</class>
In case of jboss this concerns every entity class (local - i.e. within the project You are developing or in a library). In case of Tomcat 7.x this concerns only entity classes within libraries.
Use MySQL's STR_TO_DATE()
function to parse the string that you're attempting to insert:
INSERT INTO tblInquiry (fldInquiryReceivedDateTime) VALUES
(STR_TO_DATE('5/15/2012 8:06:26 AM', '%c/%e/%Y %r'))
@zIronManBox answer works flawlessly. Although it doesn't have the capability for unselection and unseleted items in the recyclerView.
SO
add, as before, a private int selectedPos = RecyclerView.NO_POSITION; in the RecyclerView Adapter class, and under onBindViewHolder method :
@Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
viewHolder.itemView.setSelected(selectedPos == position);
}
And also in your OnClick event :
@Override
public void onClick(View view) {
notifyItemChanged(selectedPos);
selectedPos = getLayoutPosition();
notifyItemChanged(selectedPos);
}
Also add the following selector (drawable) in your layout , which includes a state_selected="false" with a transparent color:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/pressed_color" android:state_pressed="true"/>
<item android:drawable="@color/selected_color" android:state_selected="true"/>
<item android:drawable="@color/focused_color" android:state_focused="true"/>
<item android:drawable="@android:color/transparent" android:state_selected="false"/>
</selector>
Otherwise setSelected(..) will do nothing, rendering this solution useless.
I think the best option for you is to enclose both divs by another div. Then you can make it by CSS in the following way:
<html>
<head>
<style>
div.both:hover .image { border: 1px solid blue }
div.both:hover .layer { border: 1px solid blue }
</style>
</head>
<body>
<div class="section">
<div class="both">
<div class="image"><img src="myImage.jpg" /></div>
<div class="layer">Lorem Ipsum</div>
</div>
</div>
</body>
</html>
$data = file_get_contents('php://input');
echo $data;
This worked for me.
It looks like Angular has support for this now.
From the latest (v1.2.0) docs for $routeProvider.when(path, route)
:
path
can contain optional named groups with a question mark (:name?
)
document.getElementById('youridhere').click()
on windows: Go to "Add or remove programs" in control panel (or open the start menu and search for "remove program")
https://www.microsoft.com/en-us/download/details.aspx?id=14258
which leads to:
Microsoft® Visual Studio Team System 2008 Database Edition GDR R2
Hope this is helpfull
When you register a class, and use dequeueReusableCellWithIdentifier:forIndexPath:, the dequeue method is guaranteed to return a cell, so your if (cell == nil) clause is never entered. So, just do it the old way, don't register the class, and use dequeueReusableCellWithIdentifier:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"newFriendCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
//etc.
return cell;
}
As for the segue, it can't be called because you can't make a segue to a table that you've created in code, not in IB. Again, go back to the old way and use tableView:didSelectRowAtIndexPath: which will be called when you select a cell. Instantiate your detail controller there and do the trasition in code.
After edit:
I didn't see your added code there. You've implemented didDeselectRowAtIndexPath rather than didSelectRowAtIndexPath. If you change that, your segue should work.
I got resolver the problem in this way:
tree
in bash.Example
Example
I was also getting the same problem, but i uninstalled all updates of java and now it is working very fine....
XmlSerializer sr = new XmlSerializer(objectToSerialize.GetType());
TextWriter xmlWriter = new StreamWriter(filename);
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
namespaces.Add(string.Empty, string.Empty);
sr.Serialize(xmlWriter, objectToSerialize, namespaces);
No way to do this that I know of, although I'm very curious to read if anyone has a good answer. I have been thinking about adding something like this to one of the apps my company builds, but have found no good way to do it.
The one thing I can think of (although not directly on point) is that I believe you can limit the total memory usage for a COM+ application in Windows. It would require the app to be written to run in COM+, of course, but it's the closest way I know of.
The working set stuff is good (Job Objects also control working sets), but that's not total memory usage, only real memory usage (paged in) at any one time. It may work for what you want, but afaik it doesn't limit total allocated memory.
In Android Studio 3.1, you can see the errors details in the Build window.
Open up Build tab. They are somewhat hidden, you have to expand the Java compiler node. You will see the errors there.
But there is a better way to see the errors. You can click on the Toggle View button to get a better view of the error. That way you don't have to expand each node.
There is another way that symbolic links may fail you, as I discovered in my situation. If you have an SELinux system as the server and the symbolic links point to an NFS-mounted folder (other file systems may yield similar symptoms), httpd
may see the wrong contexts and refuse to serve the contents of the target folders.
In my case the SELinux context of /var/www/html
(which you can obtain with ls -Z
) is unconfined_u:object_r:httpd_sys_content_t:s0
. The symbolic links in /var/www/html
will have the same context, but their target's context, being an NFS-mounted folder, are system_u:object_r:nfs_t:s0
.
The solution is to add fscontext=unconfined_u:object_r:httpd_sys_content_t:s0
to the mount
options (e.g. # mount -t nfs -o v3,fscontext=unconfined_u:object_r:httpd_sys_content_t:s0 <IP address>:/<server path> /<mount point>
). rootcontext
is irrelevant and defcontext
is rejected by NFS. I did not try context
by itself.
Prolly a better solution out there somewhere, but this is what I did.
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<TableRow>
<TextView
android:layout_column="1"
android:text="•"></TextView>
<TextView
android:layout_column="2"
android:layout_width="wrap_content"
android:text="First line"></TextView>
</TableRow>
<TableRow>
<TextView
android:layout_column="1"
android:text="•"></TextView>
<TextView
android:layout_column="2"
android:layout_width="wrap_content"
android:text="Second line"></TextView>
</TableRow>
</TableLayout>
It works like you want, but a workaround really.
Just use $interval
Here is your code modified. http://plnkr.co/edit/m7psQ5rwx4w1yAwAFdyr?p=preview
var app = angular.module('test', []);
app.controller('TestCtrl', function ($scope, $interval) {
$scope.testValue = 0;
$interval(function() {
$scope.testValue++;
}, 500);
});
You should use <label for="">
for the checkboxes or radios, and to align checkboxes vertical-align
is enough
Try changing your markup to this
<li>
<input id="checkid" type="checkbox" value="test" />
<label for="checkid">testdata</label>
</li>
<li>
<input id="checkid2" type="checkbox" value="test" />
<label for="checkid2">testdata 2</label>
</li>
And set CSS like
input[type="checkbox"]
{
vertical-align:middle;
}
In case of long text
label,input{
display: inline-block;
vertical-align: middle;
}
Side note: In label, value of for must be the id of checkbox.
You can do in this way:
Integer i = 1;
new BigInteger("" + i);
The bootstrap css can be generated by Less. The main purpose of map file is used to link the css source code to less source code in the chrome dev tool. As we used to do .If we inspect the element in the chrome dev tool. you can see the source code of css. But if include the map file in the page with bootstrap css file. you can see the less code which apply to the element style you want to inspect.
<form (submit)="addTodo()">_x000D_
<input type="text" [(ngModel)]="text">_x000D_
</form>
_x000D_
An update for Rails 5:
gem 'protected_attributes'
doesn't seem to work anymore. But give:
gem 'protected_attributes_continued'
a try.
From the friendly Wikipedia:
The stdlib.h and stddef.h header files define a datatype called size_t which is used to represent the size of an object. Library functions that take sizes expect them to be of type size_t, and the sizeof operator evaluates to size_t.
The actual type of size_t is platform-dependent; a common mistake is to assume size_t is the same as unsigned int, which can lead to programming errors, particularly as 64-bit architectures become more prevalent.
Also, check Why size_t matters
You forgot to put z as an bind variable.
The following EXECUTE command runs a PL/SQL statement that references a stored procedure:
SQL> EXECUTE -
> :Z := EMP_SALE.HIRE('JACK','MANAGER','JONES',2990,'SALES')
Note that the value returned by the stored procedure is being return into :Z
A simple java implementation, refer to c++ std::next_permutation
:
public static void main(String[] args){
int[] list = {1,2,3,4,5};
List<List<Integer>> output = new Main().permute(list);
for(List result: output){
System.out.println(result);
}
}
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> list = new ArrayList<List<Integer>>();
int size = factorial(nums.length);
// add the original one to the list
List<Integer> seq = new ArrayList<Integer>();
for(int a:nums){
seq.add(a);
}
list.add(seq);
// generate the next and next permutation and add them to list
for(int i = 0;i < size - 1;i++){
seq = new ArrayList<Integer>();
nextPermutation(nums);
for(int a:nums){
seq.add(a);
}
list.add(seq);
}
return list;
}
int factorial(int n){
return (n==1)?1:n*factorial(n-1);
}
void nextPermutation(int[] nums){
int i = nums.length -1; // start from the end
while(i > 0 && nums[i-1] >= nums[i]){
i--;
}
if(i==0){
reverse(nums,0,nums.length -1 );
}else{
// found the first one not in order
int j = i;
// found just bigger one
while(j < nums.length && nums[j] > nums[i-1]){
j++;
}
//swap(nums[i-1],nums[j-1]);
int tmp = nums[i-1];
nums[i-1] = nums[j-1];
nums[j-1] = tmp;
reverse(nums,i,nums.length-1);
}
}
// reverse the sequence
void reverse(int[] arr,int start, int end){
int tmp;
for(int i = 0; i <= (end - start)/2; i++ ){
tmp = arr[start + i];
arr[start + i] = arr[end - i];
arr[end - i ] = tmp;
}
}
I saw that someone was wondering how to do it for another controller.
In my case I had all of my email templates in the Views/Email folder, but you could modify this to pass in the controller in which you have views associated for.
public static string RenderViewToString(Controller controller, string viewName, object model)
{
var oldController = controller.RouteData.Values["controller"].ToString();
if (controller.GetType() != typeof(EmailController))
controller.RouteData.Values["controller"] = "Email";
var oldModel = controller.ViewData.Model;
controller.ViewData.Model = model;
try
{
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindView(controller.ControllerContext, viewName,
null);
var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
viewResult.View.Render(viewContext, sw);
//Cleanup
controller.ViewData.Model = oldModel;
controller.RouteData.Values["controller"] = oldController;
return sw.GetStringBuilder().ToString();
}
}
catch (Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
throw ex;
}
}
Essentially what this does is take a controller, such as AccountController and modify it to think it's an EmailController so that the code will look in the Views/Email
folder. It's necessary to do this because the FindView
method doesn't take a straight up path as a parameter, it wants a ControllerContext
.
Once done rendering the string, it returns the AccountController back to its initial state to be used by the Response object.
I wrote the following to print a list of results to standard out based on available charsets. Note that it also tells you what line fails from a 0 based line number in case you are troubleshooting what character is causing issues.
public static void testCharset(String fileName) {
SortedMap<String, Charset> charsets = Charset.availableCharsets();
for (String k : charsets.keySet()) {
int line = 0;
boolean success = true;
try (BufferedReader b = Files.newBufferedReader(Paths.get(fileName),charsets.get(k))) {
while (b.ready()) {
b.readLine();
line++;
}
} catch (IOException e) {
success = false;
System.out.println(k+" failed on line "+line);
}
if (success)
System.out.println("************************* Successs "+k);
}
}
In your case it's definitely the crawler instance is having more Xdebug limit to trace error and debug info.
But, in other cases also errors like on PHP or core files like CodeIgniter libraries will create such a case and if you even increase the x-debug level setting it would not vanish.
So, look into your code carefully :) .
Here was the issue in my case.
I had a service class which is library in CodeIgniter. Having a function inside like this.
class PaymentService {
private $CI;
public function __construct() {
$this->CI =& get_instance();
}
public function process(){
//lots of Ci referencing here...
}
My controller as follow:
$this->load->library('PaymentService');
$this->process_(); // see I got this wrong instead it shoud be like
Function call on last line was wrong because of the typo, instead it should have been like below:
$this->Payment_service->process(); //the library class name
Then I was keeping getting the exceed error message. But I disabled XDebug but non helped. Any way please check you class name or your code for proper function calling.
This is the easiest way:
IEnumerable<myType> collection = control.Children.OfType<myType>();
where control is the root element of the window.
UNEXPAND(1) User Commands UNEXPAND(1)
NAME
unexpand - convert spaces to tabs
SYNOPSIS
unexpand [OPTION]... [FILE]...
DESCRIPTION
Convert blanks in each FILE to tabs, writing to standard output. With
no FILE, or when FILE is -, read standard input.
Mandatory arguments to long options are mandatory for short options
too.
-a, --all
convert all blanks, instead of just initial blanks
--first-only
convert only leading sequences of blanks (overrides -a)
-t, --tabs=N
have tabs N characters apart instead of 8 (enables -a)
-t, --tabs=LIST
use comma separated LIST of tab positions (enables -a)
--help display this help and exit
--version
output version information and exit
. . .
STANDARDS
The expand and unexpand utilities conform to IEEE Std 1003.1-2001
(``POSIX.1'').
Try this solution.
$mainModelData = mainModel::where('column', $value)
->join('relationModal', 'main_table_name.relation_table_column', '=', 'relation_table.id')
->orderBy('relation_table.title', 'ASC')
->with(['relationModal' => function ($q) {
$q->where('column', 'value');
}])->get();
Example:
$user = User::where('city', 'kullu')
->join('salaries', 'users.id', '=', 'salaries.user_id')
->orderBy('salaries.amount', 'ASC')
->with(['salaries' => function ($q) {
$q->where('amount', '>', '500000');
}])->get();
You can change the column name in join()
as per your database structure.
The C++ way would be to use std::stringstream or just plain string concatenations. C++ strings are mutable so the performance considerations of concatenation are less of a concern.
with regards to formatting, you can do all the same formatting on a stream, but in a different way, similar to cout
. or you can use a strongly typed functor which encapsulates this and provides a String.Format like interface e.g. boost::format
Try this:
//the code will execute in 1 3 5 7 9 seconds later
function exec() {
for(var i=0;i<5;i++) {
setTimeout(function() {
console.log(new Date()); //It's you code
},(i+i+1)*1000);
}
}
Using dynamic enums is bad no matter which way. You will have to go through the trouble of "duplicating" the data to ensure clear and easy code easy to maintain in the future.
If you start introducing automatic generated libraries, you are for sure causing more confusion to future developers having to upgrade your code than simply making your enum coded within the appropriate class object.
The other examples given sound nice and exciting, but think about the overhead on code maintenance versus what you get from it. Also, are those values going to change that frequently?
$('#myformelement').append('<input type="hidden" name="myfieldname" value="myvalue" />');
Since none of the solutions flying around really met our requirements, we came up with a simple jQuery plugin called jQuery-ClearSearch -
using it is as easy as:
<input class="clearable" type="text" placeholder="search">
<script type="text/javascript">
$('.clearable').clearSearch();
</script>
? Example: http://jsfiddle.net/wldaunfr/FERw3/
Created a shell script to solve the problem.
https://antofthy.gitlab.io/software/#logrotate_one
This script will run just the single logrotate sub-configuration file found in "/etc/logrotate.d", but include the global settings from in the global configuration file "/etc/logrotate.conf". You can also use other otpions for testing it...
For example...
logrotate_one -d syslog
No difference here, but it matters when you have a type that has a constructor.
struct S {
constexpr S(int);
};
const S s0(0);
constexpr S s1(1);
s0
is a constant, but it does not promise to be initialized at compile-time. s1
is marked constexpr
, so it is a constant and, because S
's constructor is also marked constexpr
, it will be initialized at compile-time.
Mostly this matters when initialization at runtime would be time-consuming and you want to push that work off onto the compiler, where it's also time-consuming, but doesn't slow down execution time of the compiled program
Easiest way I find is to:
Right click project
Debug as -> Maven build ...
In the goals field put -Dmaven.surefire.debug test
In the parameters put a new parameter called forkCount with a value of 0 (previously was forkMode=never but it is deprecated and doesn't work anymore)
Set your breakpoints down and run this configuration and it should hit the breakpoint.
As you've discovered, you can't do that. You can do:
libtest_LIBS =
...
if HAVE_CLIENT
libtest_LIBS += libclient.la
endif
if HAVE_SERVER
libtest_LIBS += libserver.la
endif
My case was a database corruption after a minor upgrade in mysql basically 5.0.x to 5.1.x with the DB in myisam. The same lines on query: MySQL server has gone away Error reading result set's header
After repairing & optimizing it with mysqlcheck, it returned to normal, without the need to change the socket timeout.
Use a margin to space around an element.
.box {
margin: top right bottom left;
}
.box {
margin: 10px 5px 10px 5px;
}
This adds space outside of the element. So background colours, borders etc will not be included.
If you want to add spacing within an element use padding instead. It can be called in the same way as above.
I do get the same information while debugging. Though not while I am checking the stacktrace. Most probably you would have used the optimization flag I think. Check this link - something related.
Try compiling with -g3
remove any optimization flag.
Then it might work.
HTH!
You could use an asymmetrical border to make curves with CSS.
border-radius: 50%/100px 100px 0 0;
.box {_x000D_
width: 500px; _x000D_
height: 100px; _x000D_
border: solid 5px #000;_x000D_
border-color: #000 transparent transparent transparent;_x000D_
border-radius: 50%/100px 100px 0 0;_x000D_
}
_x000D_
<div class="box"></div>
_x000D_
You can remove public keyword from your functions, because, you have to define a class in order to declare public, private or protected function
I solved it! It's a collection of configuration and update. Add these variables where they fit in build.gradle
android {
packagingOptions {
exclude 'META-INF/ASL2.0'
exclude 'META-INF/LICENSE'
exclude 'META-INF/NOTICE'
}
dexOptions {
javaMaxHeapSize "4g"
}
defaultConfig {
multiDexEnabled true
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
}
Then update to Java 8 http://tecadmin.net/install-oracle-java-8-jdk-8-ubuntu-via-ppa/
and all will be solved!
It's because of the buildTools
update and new Android studio.
Nothing else will fail.
Perl Code for Unix systems:
# Capture date from shell
my $current_date = `date +"%m/%d/%Y"`;
# Remove newline character
$current_date = substr($current_date,0,-1);
print $current_date, "\n";
This will render depending components 3 times (arrays with equal elements aren't equal):
const [msg, setMsg] = useState([""])
setMsg(["test"])
setMsg(["test"])
setMsg(["test"])
For Linux :https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip
For Mac :https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-darwin-amd64.zip
For Windows:https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-windows-amd64.zip
unzip it
for linux and mac users move file to /usr/local/bin
and execute ngrok http 80
command in the terminal
I don't have any idea about windows
So you were on the right track. Inside your componentDidMount()
you could have finished the job by implementing setInterval()
to trigger the change, but remember the way to update a components state is via setState()
, so inside your componentDidMount()
you could have done this:
componentDidMount() {
setInterval(() => {
this.setState({time: Date.now()})
}, 1000)
}
Also, you use Date.now()
which works, with the componentDidMount()
implementation I offered above, but you will get a long set of nasty numbers updating that is not human readable, but it is technically the time updating every second in milliseconds since January 1, 1970, but we want to make this time readable to how we humans read time, so in addition to learning and implementing setInterval
you want to learn about new Date()
and toLocaleTimeString()
and you would implement it like so:
class TimeComponent extends Component {
state = { time: new Date().toLocaleTimeString() };
}
componentDidMount() {
setInterval(() => {
this.setState({ time: new Date().toLocaleTimeString() })
}, 1000)
}
Notice I also removed the constructor()
function, you do not necessarily need it, my refactor is 100% equivalent to initializing site with the constructor()
function.
Except for adding the following to sqlnet.ora
SQLNET.ALLOWED_LOGON_VERSION_CLIENT = 8
SQLNET.ALLOWED_LOGON_VERSION_SERVER = 8
I also added the following to both the Client and Server, which resolved my issue
SQLNET.AUTHENTICATION_SERVICES = (NONE)
Also see post ORA-28040: No matching authentication protocol
Looks like you use %p: Print Pointers
Take a look at antlr4. It will get you much farther along in creating a tree structure than regular expressions alone.
https://github.com/antlr/grammars-v4/tree/master/calculator (calculator.g4 contains the grammar you need)
In a nutshell, you define the grammar to parse an expression, use antlr to generate java code, and add callbacks to handle evaluation when the tree is being built.
#include<stdio.h>
static char day_tab[2][13] = {
{0,31,28,31,30,31,30,31,31,30,31,30,31},
{0,31,29,31,30,31,30,31,31,30,31,30,31}
};
int main()
{
int year,month;
scanf("%d%d%d",&year,&month,&day);
printf("%d\n",day_of_year(year,month,day));
return 0;
}
int day_of_year(int year ,int month,int day)
{
int i,leap;
leap = year%4 == 0 && year%100 != 0 || year%400 == 0;
if(month < 1 || month >12)
return -1;
if (day <1 || day > day_tab[leap][month])
return -1;
for(i= 1;i<month ; i++)
{
day += day_tab[leap][year];
}
return day;
}
A relation schema is the logical definition of a table - it defines what the name of the table is, and what the name and type of each column is. It's like a plan or a blueprint. A database schema is the collection of relation schemas for a whole database.
A table is a structure with a bunch of rows (aka "tuples"), each of which has the attributes defined by the schema. Tables might also have indexes on them to aid in looking up values on certain columns.
A database is, formally, any collection of data. In this context, the database would be a collection of tables. A DBMS (Database Management System) is the software (like MySQL, SQL Server, Oracle, etc) that manages and runs a database.
You can use setScale() e.g.
double d = ...
BigDecimal db = new BigDecimal(d).setScale(12, BigDecimal.ROUND_HALF_UP);
Lets see an example with Select control
binded to: $scope.cboPais,
source: $scope.geoPaises
HTML
<select
ng-model="cboPais"
ng-options="item.strPais for item in geoPaises"
></select>
JavaScript
$http.get(strUrl2).success(function (response) {
if (response.length > 0) {
$scope.geoPaises = response; //Data source
nIndex = indexOfUnsortedArray(response, 'iPais', default_values.iPais); //array index of default value, using a custom function to search
if (nIndex >= 0) {
$scope.cboPais = response[nIndex]; //if index of array was found
} else {
$scope.cboPais = response[0]; //select the first element of array
}
$scope.geo_getDepartamentos();
}
}
For me the /**<NEWLINE>
or Shift-Alt-J (or ?-?-J on a Mac) approach works best.
I dislike seeing Javadoc comments in source code that have been auto-generated and have not been updated with real content. As far as I am concerned, such javadocs are nothing more than a waste of screen space.
IMO, it is much much better to generate the Javadoc comment skeletons one by one as you are about to fill in the details.
FileInfo.Length
will return the length of file, in bytes (not size on disk), so this is what you are looking for, I think.
A single line version using array filter and indexOf functions:
arr = arr.filter (function (value, index, array) {
return array.indexOf (value) == index;
});
Generally, this should work in Python3:
import urllib.request
..
urllib.request.get(url)
Remember that urllib and urllib2 don't work properly after Python2.
If in some mysterious cases requests don't work (happened with me), you can also try using
wget.download(url)
Related:
Here's a decent explanation/solution to find and download all pdf files on a webpage:
It probably is the # sign like tho others have mentioned because this appears to work just fine.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<select id="#ticket_category_clone">
<option value="hw">Hardware</option>
<option>fsdf</option>
<option>sfsd</option>
<option>sdfs</option>
</select>
<script type="text/javascript">
(function check() {
var e = document.getElementById("#ticket_category_clone");
var str = e.options[e.selectedIndex].text;
alert(str);
if (str === "Hardware") {
alert('Hi');
}
})();
</script>
</body>
USE
xhr.onerror = function(e){
if (XMLHttpRequest.readyState == 4) {
// HTTP error (can be checked by XMLHttpRequest.status and XMLHttpRequest.statusText)
selFoto.erroUploadFoto('Erro HTTP: '+XMLHttpRequest.statusText);
}
else if (XMLHttpRequest.readyState == 0) {
// Network error (i.e. connection refused, access denied due to CORS, etc.)
selFoto.erroUploadFoto('Erro de rede:'+XMLHttpRequest.statusText);
}
else {
selFoto.erroUploadFoto('Erro desconhecido.');
}
};
(more code below - UPLOAD IMAGE EXAMPLE)
var selFoto = {
foto: null,
upload: function(){
LoadMod.show();
var arquivo = document.frmServico.fileupload.files[0];
var formData = new FormData();
if (arquivo.type.match('image.*')) {
formData.append('upload', arquivo, arquivo.name);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'FotoViewServlet?acao=uploadFoto', true);
xhr.responseType = 'blob';
xhr.onload = function(e){
if (this.status == 200) {
selFoto.foto = this.response;
var url = window.URL || window.webkitURL;
document.frmServico.fotoid.src = url.createObjectURL(this.response);
$('#foto-id').show();
$('#div_upload_foto').hide();
$('#div_master_upload_foto').css('background-color','transparent');
$('#div_master_upload_foto').css('border','0');
Dados.foto = document.frmServico.fotoid;
LoadMod.hide();
}
else{
erroUploadFoto(XMLHttpRequest.statusText);
}
if (XMLHttpRequest.readyState == 4) {
selFoto.erroUploadFoto('Erro HTTP: '+XMLHttpRequest.statusText);
}
else if (XMLHttpRequest.readyState == 0) {
selFoto.erroUploadFoto('Erro de rede:'+XMLHttpRequest.statusText);
}
};
xhr.onerror = function(e){
if (XMLHttpRequest.readyState == 4) {
// HTTP error (can be checked by XMLHttpRequest.status and XMLHttpRequest.statusText)
selFoto.erroUploadFoto('Erro HTTP: '+XMLHttpRequest.statusText);
}
else if (XMLHttpRequest.readyState == 0) {
// Network error (i.e. connection refused, access denied due to CORS, etc.)
selFoto.erroUploadFoto('Erro de rede:'+XMLHttpRequest.statusText);
}
else {
selFoto.erroUploadFoto('Erro desconhecido.');
}
};
xhr.send(formData);
}
else{
selFoto.erroUploadFoto('');
MyCity.mensagens.push('Selecione uma imagem.');
MyCity.showMensagensAlerta();
}
},
erroUploadFoto : function(mensagem) {
selFoto.foto = null;
$('#file-upload').val('');
LoadMod.hide();
MyCity.mensagens.push('Erro ao atualizar a foto. '+mensagem);
MyCity.showMensagensAlerta();
}
};
There's backtrace()
, and backtrace_symbols()
:
From the man page:
#include <execinfo.h>
#include <stdio.h>
...
void* callstack[128];
int i, frames = backtrace(callstack, 128);
char** strs = backtrace_symbols(callstack, frames);
for (i = 0; i < frames; ++i) {
printf("%s\n", strs[i]);
}
free(strs);
...
One way to use this in a more convenient/OOP way is to save the result of backtrace_symbols()
in an exception class constructor. Thus, whenever you throw that type of exception you have the stack trace. Then, just provide a function for printing it out. For example:
class MyException : public std::exception {
char ** strs;
MyException( const std::string & message ) {
int i, frames = backtrace(callstack, 128);
strs = backtrace_symbols(callstack, frames);
}
void printStackTrace() {
for (i = 0; i < frames; ++i) {
printf("%s\n", strs[i]);
}
free(strs);
}
};
...
try {
throw MyException("Oops!");
} catch ( MyException e ) {
e.printStackTrace();
}
Ta da!
Note: enabling optimization flags may make the resulting stack trace inaccurate. Ideally, one would use this capability with debug flags on and optimization flags off.
As others have pointed out, you only need to close the outer wrapper.
BufferedReader reader = new BufferedReader(new FileReader(fileName));
There is a very slim chance that this could leak a file handle if the BufferedReader
constructor threw an exception (e.g. OutOfMemoryError
). If your app is in this state, how careful your clean up needs to be might depend on how critical it is that you don't deprive the OS of resources it might want to allocate to other programs.
The Closeable interface can be used if a wrapper constructor is likely to fail in Java 5 or 6:
Reader reader = new FileReader(fileName);
Closeable resource = reader;
try {
BufferedReader buffered = new BufferedReader(reader);
resource = buffered;
// TODO: input
} finally {
resource.close();
}
Java 7 code should use the try-with-resources pattern:
try (Reader reader = new FileReader(fileName);
BufferedReader buffered = new BufferedReader(reader)) {
// TODO: input
}
There is a nifty plugin built from yonran
that can do the detection. Here is his previously answered question on StackOverflow. It works for most of the browsers. Application is as simple as this:
window.onresize = function onresize() {
var r = DetectZoom.ratios();
zoomLevel.innerHTML =
"Zoom level: " + r.zoom +
(r.zoom !== r.devicePxPerCssPx
? "; device to CSS pixel ratio: " + r.devicePxPerCssPx
: "");
}
The above answer is useful but in graphs, it is difficult to distinguish between darker gradients of black. One alternative I found is to use gradients of gray colors as follows
palette(gray.colors(10, 0.9, 0.4))
plot(rep(1,10),col=1:10,pch=19,cex=3))
More info on gray scale here.
Added
When I used the code above for different colours like blue and black, the gradients were not that clear.
heat.colors()
seems more useful.
This document has more detailed information and options. pdf
If you are creating many graphs, you could be tired of typing for each graph the lines of code controlling for the size of the titles and texts. What I typically do is creating an object (of class "theme" "gg") that defines the desired theme characteristics. You can do that at the beginning of your code.
My_Theme = theme(
axis.title.x = element_text(size = 16),
axis.text.x = element_text(size = 14),
axis.title.y = element_text(size = 16))
Next, all you will have to do is adding My_Theme to your graphs.
g + My_Theme
if you have another graph, g1, just write:
g1 + My_Theme
and so on.
In the load events, use Me.Hide
.
In WebBrowser1.DocuementCompleted, use Me.Show
Considering that in most cases you don't want your entire data contract to have types supplied, but only those which are containing an abstract or interface, or list thereof; and also considering these instances are very rare and easily identifiable within your data entities, the easiest and least verbose way is to use
[JsonProperty(ItemTypeNameHandling = TypeNameHandling.Objects)]
public IEnumerable<ISomeInterface> Items { get; set; }
as attribute on your property containing the enumerable/list/collection. This will target only that list, and only append type information for the contained objects, like this:
{
"Items": [
{
"$type": "Namespace.ClassA, Assembly",
"Property": "Value"
},
{
"$type": "Namespace.ClassB, Assembly",
"Property": "Value",
"Additional_ClassB_Property": 3
}
]
}
Clean, simple, and located where the complexity of your data model is introduced, instead of hidden away in some converter.
I have found that SpinWait works pretty well for this.
var task = Task.Run(()=>DoSomethingAsyncronous());
if(!SpinWait.SpinUntil(()=>task.IsComplete, TimeSpan.FromSeconds(30)))
{//Task didn't complete within 30 seconds, fail...
return false;
}
return true;
The above approach doesn't need to use .Result or .Wait(). It also lets you specify a timeout so that you're not stuck forever in case the task never completes.
It is only required if you aren't using the default values for version
and encoding
(which you are in that example).
I did it! Using <intent-filter>
. Put the following into your manifest file:
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:host="www.youtube.com" android:scheme="http" />
</intent-filter>
This works perfectly!
In XML file, you need to add following additional attributes in a TextView to get a marquee like feature:
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
android:scrollHorizontally="true"
android:singleLine="true"
In MainActivity.java file, you can get the reference of this TextView by using findViewById() and you can set the following property to this TextView to make it appear like a marquee text:
setSelected(true);
That's all you need.
TL;DR No, it can't be done automatically. Yes, it is possible.
import matplotlib.pyplot as plt
my_colors = plt.rcParams['axes.prop_cycle']() # <<< note that we CALL the prop_cycle
fig, axes = plt.subplots(2,3)
for ax in axes.flatten(): ax.plot((0,1), (0,1), **next(my_colors))
Each plot (axes
) in a figure (figure
) has its own cycle of colors — if you don't force a different color for each plot, all the plots share the same order of colors but, if we stretch a bit what "automatically" means, it can be done.
The OP wrote
[...] I have to identify each plot with a different color which should be automatically generated by [Matplotlib].
But... Matplotlib automatically generates different colors for each different curve
In [10]: import numpy as np
...: import matplotlib.pyplot as plt
In [11]: plt.plot((0,1), (0,1), (1,2), (1,0));
Out[11]:
So why the OP request? If we continue to read, we have
Can you please give me a method to put different colors for different plots in the same figure?
and it make sense, because each plot (each axes
in Matplotlib's parlance) has its own color_cycle
(or rather, in 2018, its prop_cycle
) and each plot (axes
) reuses the same colors in the same order.
In [12]: fig, axes = plt.subplots(2,3)
In [13]: for ax in axes.flatten():
...: ax.plot((0,1), (0,1))
If this is the meaning of the original question, one possibility is to explicitly name a different color for each plot.
If the plots (as it often happens) are generated in a loop we must have an additional loop variable to override the color automatically chosen by Matplotlib.
In [14]: fig, axes = plt.subplots(2,3)
In [15]: for ax, short_color_name in zip(axes.flatten(), 'brgkyc'):
...: ax.plot((0,1), (0,1), short_color_name)
Another possibility is to instantiate a cycler object
from cycler import cycler
my_cycler = cycler('color', ['k', 'r']) * cycler('linewidth', [1., 1.5, 2.])
actual_cycler = my_cycler()
fig, axes = plt.subplots(2,3)
for ax in axes.flat:
ax.plot((0,1), (0,1), **next(actual_cycler))
Note that type(my_cycler)
is cycler.Cycler
but type(actual_cycler)
is itertools.cycle
.
Too much code for this task, checkout this library https://github.com/kodart/Httpzoid Is uses GSON internally and provides API that works with objects. All JSON details are hidden.
Http http = HttpFactory.create(context);
http.get("http://example.com/users")
.handler(new ResponseHandler<User[]>() {
@Override
public void success(User[] users, HttpResponse response) {
}
}).execute();
Try this:
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
If you want to inform your frontend about a validation error, try to return json:
dataType: 'json',
success: function(data, textStatus, jqXHR) {
console.log(data.error);
}
Your asp script schould return:
{"error": true}
You can use jQuery bind:
$(window).bind('keydown', function(e){
if (e.keyCode == 37) {
console.log('left');
} else if (e.keyCode == 38) {
console.log('up');
} else if (e.keyCode == 39) {
console.log('right');
} else if (e.keyCode == 40) {
console.log('down');
}
});
Depends on how you hid it.
If you used the CSS visibility
value then
$('#test1').css('visibility', 'visible');
If you used CSS `display'
$('#test1').css('display', 'block'); //or inline or any of the other combos
You might even have made it opacity = 0
$('#test1').css('opacity', '1');
You can enter these module class suffixes for any module to better control where it will show or be hidden.
.visible-phone
.visible-tablet
.visible-desktop
.hidden-phone
.hidden-tablet
.hidden-desktop
http://twitter.github.com/bootstrap/scaffolding.html scroll to bottom
Lexical cast is very nice.
#include <boost/lexical_cast.hpp>
#include <iostream>
#include <string>
using std::endl;
using std::cout;
using std::string;
using boost::lexical_cast;
int main() {
string str = "0.6";
double dub = lexical_cast<double>(str);
cout << dub << endl;
}
You need to use double apostrophe instead of single in the "You''re", eg:
String text = java.text.MessageFormat.format("You''re about to delete {0} rows.", 5);
System.out.println(text);
There are a few ways to accomplish that:
# Rename the local branch to the new name
git branch -m <old_name> <new_name>
# Delete the old branch on remote - where <remote> is, for example, origin
git push <remote> --delete <old_name>
# Or shorter way to delete remote branch [:]
git push <remote> :<old_name>
# Prevent git from using the old name when pushing in the next step.
# Otherwise, git will use the old upstream name instead of <new_name>.
git branch --unset-upstream <old_name>
# Push the new branch to remote
git push <remote> <new_name>
# Reset the upstream branch for the new_name local branch
git push <remote> -u <new_name>
Credit: ptim
# In this option, we will push the branch to the remote with the new name
# While keeping the local name as is
git push <remote> <remote>/<old_name>:refs/heads/<new_name> :<old_name>
When you use the git branch -m
(move), Git is also updating your tracking branch with the new name.
git remote rename legacy legacy
git remote rename
is trying to update your remote section in your configuration file. It will rename the remote with the given name to the new name, but in your case, it did not find any, so the renaming failed.
But it will not do what you think; it will rename your local configuration remote name and not the remote branch.
Note Git servers might allow you to rename Git branches using the web interface or external programs (like Sourcetree, etc.), but you have to keep in mind that in Git all the work is done locally, so it's recommended to use the above commands to the work.
Do you mean like:
import groovy.json.*
class Me {
String name
}
def o = new Me( name: 'tim' )
println new JsonBuilder( o ).toPrettyString()
it should works at least in pyspark 2.4
tdata = tdata.withColumn("Age", when((tdata.Age == "") & (tdata.Survived == "0") , "NewValue").otherwise(tdata.Age))
From the command line you can convert a notebook to python with this command:
jupyter nbconvert --to python nb.ipynb
https://github.com/jupyter/nbconvert
You may have to install the python mistune package:
sudo pip install -U mistune
Simple one
To remove it:
.form-control, .btn {
box-shadow: none !important;
outline: none !important;
}
To change it
.form-control, .btn {
box-shadow: new-value !important;
outline: new-value !important;
}
You can use a regular expression or some manual string fiddling, but I think I prefer:
date("d/m/Y", strtotime($str));
I had this exact problem, but with a tableView inside a tableView cell. Nothing worked from the numerous answers from above. A very odd and simple thing worked:
- Put the estimated heights before assigning the delegate for the tableView!!
override func awakeFromNib() {
super.awakeFromNib()
tableView.estimatedRowHeight = 58
tableView.estimatedSectionHeaderHeight = 45
tableView.estimatedSectionFooterHeight = 10
tableView.dataSource = self
tableView.delegate = self
}
Putting the estimates after the delegate assignment, caused my inner tableView to have an odd white space above the header. I hope it helps someone here.
You can try this:
<div ng-app="app">
<div ng-controller="AppCtrl">
<a my-dir ng-repeat="user in users" ng-click="fxn()">{{user.name}}</a>
</div>
</div>
<script>
var app = angular.module('app', []);
function AppCtrl($scope) {
$scope.users = [{ name: 'John', id: 1 }, { name: 'anonymous' }];
$scope.fxn = function () {
alert('It works');
};
}
app.directive("myDir", function ($compile) {
return {
scope: {ngClick: '='}
};
});
</script>
Actually I don't know you want to this.
try this
INSERT INTO my_table (my_column)
SELECT
(random() * 10) + 1
;
Remove this line :
android:background="@drawable/transparent">
And in your activity class set
ImageButton btn = (ImageButton)findViewById(R.id.previous);
btn.setAlpha(100);
You can set alpha level 0 to 255
o means transparent and 255 means opaque.
I had this error and then I realized I was logged in with my personal Microsoft account instead of my work account.
Hope this helps.
There is a lot of error in your program.
Calculation of index. I think it should be Math.random()%deck.length
In the display of card. According to me, you should make a class of card which has rank suit and make the array of that class type
If you want I can give you the Complete structure of that but it is better if u make it by yourself
Indexing a list is done using double bracket, i.e. hypo_list[[1]]
(e.g. have a look here: http://www.r-tutor.com/r-introduction/list). BTW: read.table
does not return a table but a dataframe (see value section in ?read.table
). So you will have a list of dataframes, rather than a list of table objects. The principal mechanism is identical for tables and dataframes though.
Note: In R, the index for the first entry is a 1
(not 0
like in some other languages).
Dataframes
l <- list(anscombe, iris) # put dfs in list
l[[1]] # returns anscombe dataframe
anscombe[1:2, 2] # access first two rows and second column of dataset
[1] 10 8
l[[1]][1:2, 2] # the same but selecting the dataframe from the list first
[1] 10 8
Table objects
tbl1 <- table(sample(1:5, 50, rep=T))
tbl2 <- table(sample(1:5, 50, rep=T))
l <- list(tbl1, tbl2) # put tables in a list
tbl1[1:2] # access first two elements of table 1
Now with the list
l[[1]] # access first table from the list
1 2 3 4 5
9 11 12 9 9
l[[1]][1:2] # access first two elements in first table
1 2
9 11
Note that this isn't perfect, since if you had something like, say, <a title=">">
it would break. However, it's about the closest you'd get in non-library Python without a really complex function:
import re
TAG_RE = re.compile(r'<[^>]+>')
def remove_tags(text):
return TAG_RE.sub('', text)
However, as lvc mentions xml.etree
is available in the Python Standard Library, so you could probably just adapt it to serve like your existing lxml
version:
def remove_tags(text):
return ''.join(xml.etree.ElementTree.fromstring(text).itertext())
poem = '''\
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
'''
f = open('poem.txt', 'w') # open for 'w'riting
f.write(poem) # write text to file
f.close() # close the file
How It Works: First, open a ?le by using the built-in open function and specifying the name of the ?le and the mode in which we want to open the ?le. The mode can be a read mode (’r’), write mode (’w’) or append mode (’a’). We can also specify whether we are reading, writing, or appending in text mode (’t’) or binary mode (’b’). There are actually many more modes available and help(open) will give you more details about them. By default, open() considers the ?le to be a ’t’ext ?le and opens it in ’r’ead mode. In our example, we ?rst open the ?le in write text mode and use the write method of the ?le object to write to the ?le and then we ?nally close the ?le.
The above example is from the book "A Byte of Python" by Swaroop C H. swaroopch.com
I had the error of
No provider for Router
It happens when you try to navigate in any service.ts
this.router.navigate(['/home']);
like codes in services cause that error.
You should handle navigating in your components. for example: at login.component
login().subscribe(
(res) => this.router.navigate(['/home']),
(error: any) => this.handleError(error));
Annoying errors happens when we are newbie :)
Another option is to use datediff
from dateutils
(http://www.fresse.org/dateutils/#datediff):
$ datediff 10:33:56 10:36:10
134s
$ datediff 10:33:56 10:36:10 -f%H:%M:%S
0:2:14
$ datediff 10:33:56 10:36:10 -f%0H:%0M:%0S
00:02:14
You could also use gawk
. mawk
1.3.4 also has strftime
and mktime
but older versions of mawk
and nawk
don't.
$ TZ=UTC0 awk 'BEGIN{print strftime("%T",mktime("1970 1 1 10 36 10")-mktime("1970 1 1 10 33 56"))}'
00:02:14
Or here's another way to do it with GNU date
:
$ date -ud@$(($(date -ud'1970-01-01 10:36:10' +%s)-$(date -ud'1970-01-01 10:33:56' +%s))) +%T
00:02:14
There is an excellent summary of this feature in the article The For-Each Loop. It shows by example how using the for-each style can produce clearer code that is easier to read and write.
If you want to store formatted as a string variable and reuse it to text view isn't possible
If you aren't applying formatting, you can set TextView text directly by calling setText(java.lang.CharSequence). In some cases, however, you may want to create a styled text resource that is also used as a format string. Normally, this doesn't work because the format(String, Object...) and getString(int, Object...) methods strip all the style information from the string. The work-around to this is to write the HTML tags with escaped entities, which are then recovered with fromHtml(String), after the formatting takes place.
by from docs so alternatively store the string id and everyttime bind get string from using Htlm.fromHtml().. method.
ex:
Kotlin extention
fun Context.getStringFromResource(stringId: Int): Spanned {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Html.fromHtml(java.lang.String.format(resources.getString(stringId)),
Html.FROM_HTML_MODE_COMPACT)
} else {
Html.fromHtml(java.lang.String.format(resources.getString(stringId)))
}
}
In code:
getStringFromResource(id)
Avoid /etc/*release* files and run this command instead, it is far more reliable and gives more details:
rpm -qia '*release*'
Here is a code snippet, that counts number of files in a particular HDFS directory (I used this to determine how many reducers to use in a particular ETL code). You can easily modify this to suite your needs.
private int calculateNumberOfReducers(String input) throws IOException {
int numberOfReducers = 0;
Path inputPath = new Path(input);
FileSystem fs = inputPath.getFileSystem(getConf());
FileStatus[] statuses = fs.globStatus(inputPath);
for(FileStatus status: statuses) {
if(status.isDirectory()) {
numberOfReducers += getNumberOfInputFiles(status, fs);
} else if(status.isFile()) {
numberOfReducers ++;
}
}
return numberOfReducers;
}
/**
* Recursively determines number of input files in an HDFS directory
*
* @param status instance of FileStatus
* @param fs instance of FileSystem
* @return number of input files within particular HDFS directory
* @throws IOException
*/
private int getNumberOfInputFiles(FileStatus status, FileSystem fs) throws IOException {
int inputFileCount = 0;
if(status.isDirectory()) {
FileStatus[] files = fs.listStatus(status.getPath());
for(FileStatus file: files) {
inputFileCount += getNumberOfInputFiles(file, fs);
}
} else {
inputFileCount ++;
}
return inputFileCount;
}
I experienced the same issue when trying to install tensorflow from a jupyter notebook using Anaconda. --user did not work.
conda install tensorflow
worked for me, and I didn't have to change any security settings.
If you do a lot with timing, I can recommend this little (20 line) context manager:
You code could look like this then:
#!/usr/bin/env python
# coding: utf-8
from timer import Timer
if __name__ == '__main__':
a, record = None, []
while not a == '':
with Timer() as t: # everything in the block will be timed
a = input('Type: ')
record.append(t.elapsed_s)
# drop the last item (makes a copy of the list):
record = record[:-1]
# or just delete it:
# del record[-1]
Just for reference, here's the content of the Timer context manager in full:
from timeit import default_timer
class Timer(object):
""" A timer as a context manager. """
def __init__(self):
self.timer = default_timer
# measures wall clock time, not CPU time!
# On Unix systems, it corresponds to time.time
# On Windows systems, it corresponds to time.clock
def __enter__(self):
self.start = self.timer() # measure start time
return self
def __exit__(self, exc_type, exc_value, exc_traceback):
self.end = self.timer() # measure end time
self.elapsed_s = self.end - self.start # elapsed time, in seconds
self.elapsed_ms = self.elapsed_s * 1000 # elapsed time, in milliseconds
I just came accross the answer from Lizard which is extremely helpful - especially when you do some sorting. Isn't is beautiful how many chars we need to say mostly the same ;)
If anyone else if looking for a all-in solution (as far as the comments above tell), here's the copy&paste:
/**
* Replace language-specific characters by ASCII-equivalents.
* @param string $s
* @return string
*/
public static function normalizeChars($s) {
$replace = array(
'?'=>'-', '?'=>'-', '?'=>'-', '?'=>'-',
'A'=>'A', 'A'=>'A', 'À'=>'A', 'Ã'=>'A', 'Á'=>'A', 'Æ'=>'A', 'Â'=>'A', 'Å'=>'A', 'Ä'=>'Ae',
'Þ'=>'B',
'C'=>'C', '?'=>'C', 'Ç'=>'C',
'È'=>'E', 'E'=>'E', 'É'=>'E', 'Ë'=>'E', 'Ê'=>'E',
'G'=>'G',
'I'=>'I', 'Ï'=>'I', 'Î'=>'I', 'Í'=>'I', 'Ì'=>'I',
'L'=>'L',
'Ñ'=>'N', 'N'=>'N',
'Ø'=>'O', 'Ó'=>'O', 'Ò'=>'O', 'Ô'=>'O', 'Õ'=>'O', 'Ö'=>'Oe',
'S'=>'S', 'S'=>'S', '?'=>'S', 'Š'=>'S',
'?'=>'T',
'Ù'=>'U', 'Û'=>'U', 'Ú'=>'U', 'Ü'=>'Ue',
'Ý'=>'Y',
'Z'=>'Z', 'Ž'=>'Z', 'Z'=>'Z',
'â'=>'a', 'a'=>'a', 'a'=>'a', 'á'=>'a', 'a'=>'a', 'ã'=>'a', 'A'=>'a', '?'=>'a', '?'=>'a', 'å'=>'a', 'à'=>'a', '?'=>'a', '?'=>'a', 'A'=>'a', '?'=>'a', 'a'=>'a', 'ä'=>'ae', 'æ'=>'ae', '?'=>'ae', '?'=>'ae',
'?'=>'b', '?'=>'b', '?'=>'b', 'þ'=>'b',
'c'=>'c', 'C'=>'c', 'C'=>'c', 'c'=>'c', 'ç'=>'c', '?'=>'c', '?'=>'c', 'c'=>'c', '?'=>'c', 'C'=>'c', 'c'=>'c', '?'=>'ch', '?'=>'ch',
'?'=>'d', 'd'=>'d', 'Ð'=>'d', 'D'=>'d', 'd'=>'d', '?'=>'d', '?'=>'D', 'ð'=>'d',
'?'=>'e', '?'=>'e', '?'=>'e', '?'=>'e', '?'=>'e', 'e'=>'e', 'e'=>'e', 'e'=>'e', 'E'=>'e', 'E'=>'e', 'e'=>'e', 'e'=>'e', 'E'=>'e', '?'=>'e', 'E'=>'e', 'ê'=>'e', '?'=>'e', 'è'=>'e', 'ë'=>'e', 'é'=>'e',
'?'=>'f', 'ƒ'=>'f', '?'=>'f',
'g'=>'g', 'G'=>'g', 'G'=>'g', 'G'=>'g', '?'=>'g', '?'=>'g', 'g'=>'g', 'g'=>'g', '?'=>'g', '?'=>'g', '?'=>'g', 'g'=>'g',
'?'=>'h', 'h'=>'h', '?'=>'h', 'H'=>'h', 'H'=>'h', 'h'=>'h', '?'=>'h', '?'=>'h',
'î'=>'i', 'ï'=>'i', 'í'=>'i', 'ì'=>'i', 'i'=>'i', 'i'=>'i', 'i'=>'i', 'I'=>'i', '?'=>'i', 'i'=>'i', 'i'=>'i', 'I'=>'i', 'I'=>'i', '?'=>'i', 'I'=>'i', '?'=>'i', '?'=>'i', 'I'=>'i', '?'=>'i', '?'=>'i', '?'=>'i', 'i'=>'i', '?'=>'ij', '?'=>'ij',
'?'=>'j', '?'=>'j', 'J'=>'j', 'j'=>'j', '?'=>'ja', '?'=>'ja', '?'=>'je', '?'=>'je', '?'=>'jo', '?'=>'jo', '?'=>'ju', '?'=>'ju',
'?'=>'k', '?'=>'k', 'K'=>'k', '?'=>'k', '?'=>'k', 'k'=>'k', '?'=>'k',
'?'=>'l', '?'=>'l', '?'=>'l', 'l'=>'l', 'l'=>'l', 'l'=>'l', 'L'=>'l', 'L'=>'l', '?'=>'l', 'L'=>'l', 'l'=>'l', '?'=>'l',
'?'=>'m', '?'=>'m', '?'=>'m', '?'=>'m',
'ñ'=>'n', '?'=>'n', 'N'=>'n', '?'=>'n', '?'=>'n', '?'=>'n', '?'=>'n', 'n'=>'n', '?'=>'n', 'n'=>'n', '?'=>'n', 'N'=>'n', 'n'=>'n',
'?'=>'o', '?'=>'o', 'o'=>'o', 'õ'=>'o', 'ô'=>'o', 'O'=>'o', 'o'=>'o', 'O'=>'o', 'O'=>'o', 'o'=>'o', 'ø'=>'o', '?'=>'o', 'o'=>'o', 'ò'=>'o', '?'=>'o', 'O'=>'o', 'o'=>'o', 'ó'=>'o', 'O'=>'o', 'œ'=>'oe', 'Œ'=>'oe', 'ö'=>'oe',
'?'=>'p', '?'=>'p', '?'=>'p', '?'=>'p',
'?'=>'q',
'r'=>'r', 'r'=>'r', 'R'=>'r', 'r'=>'r', 'R'=>'r', '?'=>'r', 'R'=>'r', '?'=>'r', '?'=>'r',
'?'=>'s', '?'=>'s', 'S'=>'s', 'š'=>'s', 's'=>'s', '?'=>'s', 's'=>'s', '?'=>'s', 's'=>'s', '?'=>'sch', '?'=>'sch', '?'=>'sh', '?'=>'sh', 'ß'=>'ss',
'?'=>'t', '?'=>'t', 't'=>'t', '?'=>'t', 't'=>'t', 't'=>'t', 'T'=>'t', '?'=>'t', '?'=>'t', 'T'=>'t', 'T'=>'t', '™'=>'tm',
'u'=>'u', '?'=>'u', 'U'=>'u', 'u'=>'u', 'U'=>'u', 'u'=>'u', 'U'=>'u', 'U'=>'u', 'u'=>'u', 'U'=>'u', 'u'=>'u', 'U'=>'u', 'U'=>'u', 'u'=>'u', 'u'=>'u', 'U'=>'u', 'U'=>'u', 'u'=>'u', 'U'=>'u', 'ù'=>'u', 'ú'=>'u', 'û'=>'u', '?'=>'u', 'u'=>'u', 'u'=>'u', 'U'=>'u', 'U'=>'u', 'u'=>'u', 'u'=>'u', 'ü'=>'ue',
'?'=>'v', '?'=>'v', '?'=>'v',
'?'=>'w', 'w'=>'w', 'W'=>'w',
'?'=>'y', 'y'=>'y', 'ý'=>'y', 'ÿ'=>'y', 'Ÿ'=>'y', 'Y'=>'y',
'?'=>'y', 'ž'=>'z', '?'=>'z', '?'=>'z', 'z'=>'z', '?'=>'z', 'z'=>'z', '?'=>'z', '?'=>'zh', '?'=>'zh'
);
return strtr($s, $replace);
}
Note some slight changes regarding the German umlauts (ä => ae)
Edit: Included more characters based on the posting from user3682119 (except for the copyright symbol) and the comment from daker.
Have you tried opening in notepad++ (or another editor) and converting/saving us to UTF-8?
See: notepad++ converting ansi encoded file to utf-8
Another option may be to use textwrangle to open and save the file as UTF-8: http://www.barebones.com/products/textwrangler/
There is a "variant" to pax' answer... ;-)
int i = -1;
for(String s : stringArray) {
doSomethingWith(s, ++i);
}
From here:
One way to conserve system resources is to configure idle time-out settings for the worker processes in an application pool. When these settings are configured, a worker process will shut down after a specified period of inactivity. The default value for idle time-out is 20 minutes.
Also check Why is the IIS default app pool recycle set to 1740 minutes?
If you have a just a few sites on your server and you want them to always load fast then set this to zero. Otherwise, when you have 20 minutes without any traffic then the app pool will terminate so that it can start up again on the next visit. The problem is that the first visit to an app pool needs to create a new w3wp.exe worker process which is slow because the app pool needs to be created, ASP.NET or another framework needs to be loaded, and then your application needs to be loaded. That can take a few seconds. Therefore I set that to 0 every chance I have, unless it’s for a server that hosts a lot of sites that don’t always need to be running.
You should really read Wikipedia for in-depth understanding. In short, Cloud computing means you develop/run your software remotely on remote platform. This can be either using remote virtual infrastructure (amazon EC2), remote platform (google app engine), or remote application (force.com or gmail.com).
Grid computing means using many physical hardwares to do computations (in the broad sense) as if it was a single hardware. This means that you can run your application on several distinct machines at the same time.
not very accurate but enough to get you started.
Encoding an image to base64 will make it about 30% bigger.
See the details in the wikipedia article about the Data URI scheme, where it states:
Base64-encoded data URIs are 1/3 larger in size than their binary equivalent. (However, this overhead is reduced to 2-3% if the HTTP server compresses the response using gzip)
Try:
output=$(ps -ef | awk '/siebsvc –s siebsrvr/ && !/awk/ { a++ } END { print a }'); echo $output
Wrapping your command in $( )
tells the shell to run that command, instead of attempting to set the command itself to the variable named "output". (Note that you could also use backticks `command`.)
I can highly recommend http://tldp.org/LDP/abs/html/commandsub.html to learn more about command substitution.
Also, as 1_CR correctly points out in a comment, the extra space between the equals sign and the assignment is causing it to fail. Here is a simple example on my machine of the behavior you are experiencing:
jed@MBP:~$ foo=$(ps -ef |head -1);echo $foo
UID PID PPID C STIME TTY TIME CMD
jed@MBP:~$ foo= $(ps -ef |head -1);echo $foo
-bash: UID: command not found
UID PID PPID C STIME TTY TIME CMD
My answer provides a ways to run a subset of test in different scenarios.
pytest
To run all the tests from one directory, use the directory as a parameter to
pytest
:
pytest tests/my-directory
To run a file full of tests, list the file with the relative path as a parameter to pytest
:
pytest tests/my-directory/test_demo.py
To run a single test function, add ::
and the test function name:
pytest -v tests/my-directory/test_demo.py::test_specific_function
-v
is used so you can see which function was run.
To run just a class, do like we did with functions and add ::
, then the class name to the file parameter:
pytest -v tests/my-directory/test_demo.py::TestClassName
If you don't want to run all of a test class, just one method, just add
another ::
and the method name:
pytest -v tests/my-directory/test_demo.py::TestClassName::test_specific_method
The -k
option enables you to pass in an expression to run tests that have
certain names specified by the expression as a substring of the test name.
It is possible to use and, or, and not to create complex expressions.
For example, to run all of the functions that have _raises in their name:
pytest -v -k _raises
You should chain the replace() together instead of assigning the result and replacing again.
var strMessage1 = document.getElementById("element1") ;
strMessage1.innerHTML = strMessage1.innerHTML
.replace(/aaaaaa./g,'<a href=\"http://www.google.com/')
.replace(/.bbbbbb/g,'/world\">Helloworld</a>');
See DEMO.
Ctrl+a followed by k will "kill" the current screen session.
Extract characters from a string:
var str = "Hello world!";
var res = str.substring(1,4);
The result of res
will be:
ell
http://www.w3schools.com/jsref/jsref_substring.asp
$('.dep_buttons').mouseover(function(){
$(this).text().substring(0,25);
if($(this).text().length > 30) {
$(this).stop().animate({height:"150px"},150);
}
$(".dep_buttons").mouseout(function(){
$(this).stop().animate({height:"40px"},150);
});
});
I Just put CSS in my <div>
now working in code
position: relative; top: -22px;
The reason it has no effect is because at the link-time the linker tries to resolve the extern definition (in your case extern int f()
). It doesn't matter if it finds it in the same file or a different file, as long as it is found.
Hope this answers your question.
There is a nuance to updating tables then updating the DBML... Foreign key relationships are not immediately always brought over if changes are made to existing tables. The work around is to do a build of the project and then re-add the tables again. I reported this to MS and its being fixed for VS2010.
DBML display does not show new foreign key constraints
Note that the instructions given in the main answer are not clear. To update the table
This ...
horse = Horse.find(:first,:offset=>rand(Horse.count))
unless @suggested_horses.exists?(horse.id)
@suggested_horses<< horse
end
Should probably be this ...
horse = Horse.find(:first,:offset=>rand(Horse.count))
unless @suggested_horses.include?(horse)
@suggested_horses<< horse
end
I would use itertools.chain
- this will also cater for > 1 element in each sublist:
from itertools import chain
list(chain.from_iterable([[180.0], [173.8], [164.2], [156.5], [147.2], [138.2]]))
Here are charts updated as of the date of this posting ("unknown platform" chart is Internet Explorer 11.15.16299.0):
From these results, it seems that the preallocate 1 method is the safest cross-browser bet.
http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_now
"NOW() returns a constant time that indicates the time at which the statement began to execute. (Within a stored routine or trigger, NOW() returns the time at which the routine or triggering statement began to execute.) This differs from the behavior for SYSDATE(), which returns the exact time at which it executes as of MySQL 5.0.13. "
There are a few options...
Object.defineProperty(myArray, "push", {
enumerable: false, // hide from for...in
configurable: false, // prevent further meddling...
writable: false, // see above ^
value: function () {
for (var i = 0, n = this.length, l = arguments.length; i < l; i++, n++) {
RaiseMyEvent(this, n, this[n] = arguments[i]); // assign/raise your event
}
return n;
}
});
1 Alternatively, if you'd like to target all arrays, you could override Array.prototype.push()
. Use caution, though; other code in your environment may not like or expect that kind of modification. Still, if a catch-all sounds appealing, just replace myArray
with Array.prototype
.
Now, that's just one method and there are lots of ways to change array content. We probably need something more comprehensive...
function ObservableArray(items) {
var _self = this,
_array = [],
_handlers = {
itemadded: [],
itemremoved: [],
itemset: []
};
function defineIndexProperty(index) {
if (!(index in _self)) {
Object.defineProperty(_self, index, {
configurable: true,
enumerable: true,
get: function() {
return _array[index];
},
set: function(v) {
_array[index] = v;
raiseEvent({
type: "itemset",
index: index,
item: v
});
}
});
}
}
function raiseEvent(event) {
_handlers[event.type].forEach(function(h) {
h.call(_self, event);
});
}
Object.defineProperty(_self, "addEventListener", {
configurable: false,
enumerable: false,
writable: false,
value: function(eventName, handler) {
eventName = ("" + eventName).toLowerCase();
if (!(eventName in _handlers)) throw new Error("Invalid event name.");
if (typeof handler !== "function") throw new Error("Invalid handler.");
_handlers[eventName].push(handler);
}
});
Object.defineProperty(_self, "removeEventListener", {
configurable: false,
enumerable: false,
writable: false,
value: function(eventName, handler) {
eventName = ("" + eventName).toLowerCase();
if (!(eventName in _handlers)) throw new Error("Invalid event name.");
if (typeof handler !== "function") throw new Error("Invalid handler.");
var h = _handlers[eventName];
var ln = h.length;
while (--ln >= 0) {
if (h[ln] === handler) {
h.splice(ln, 1);
}
}
}
});
Object.defineProperty(_self, "push", {
configurable: false,
enumerable: false,
writable: false,
value: function() {
var index;
for (var i = 0, ln = arguments.length; i < ln; i++) {
index = _array.length;
_array.push(arguments[i]);
defineIndexProperty(index);
raiseEvent({
type: "itemadded",
index: index,
item: arguments[i]
});
}
return _array.length;
}
});
Object.defineProperty(_self, "pop", {
configurable: false,
enumerable: false,
writable: false,
value: function() {
if (_array.length > -1) {
var index = _array.length - 1,
item = _array.pop();
delete _self[index];
raiseEvent({
type: "itemremoved",
index: index,
item: item
});
return item;
}
}
});
Object.defineProperty(_self, "unshift", {
configurable: false,
enumerable: false,
writable: false,
value: function() {
for (var i = 0, ln = arguments.length; i < ln; i++) {
_array.splice(i, 0, arguments[i]);
defineIndexProperty(_array.length - 1);
raiseEvent({
type: "itemadded",
index: i,
item: arguments[i]
});
}
for (; i < _array.length; i++) {
raiseEvent({
type: "itemset",
index: i,
item: _array[i]
});
}
return _array.length;
}
});
Object.defineProperty(_self, "shift", {
configurable: false,
enumerable: false,
writable: false,
value: function() {
if (_array.length > -1) {
var item = _array.shift();
delete _self[_array.length];
raiseEvent({
type: "itemremoved",
index: 0,
item: item
});
return item;
}
}
});
Object.defineProperty(_self, "splice", {
configurable: false,
enumerable: false,
writable: false,
value: function(index, howMany /*, element1, element2, ... */ ) {
var removed = [],
item,
pos;
index = index == null ? 0 : index < 0 ? _array.length + index : index;
howMany = howMany == null ? _array.length - index : howMany > 0 ? howMany : 0;
while (howMany--) {
item = _array.splice(index, 1)[0];
removed.push(item);
delete _self[_array.length];
raiseEvent({
type: "itemremoved",
index: index + removed.length - 1,
item: item
});
}
for (var i = 2, ln = arguments.length; i < ln; i++) {
_array.splice(index, 0, arguments[i]);
defineIndexProperty(_array.length - 1);
raiseEvent({
type: "itemadded",
index: index,
item: arguments[i]
});
index++;
}
return removed;
}
});
Object.defineProperty(_self, "length", {
configurable: false,
enumerable: false,
get: function() {
return _array.length;
},
set: function(value) {
var n = Number(value);
var length = _array.length;
if (n % 1 === 0 && n >= 0) {
if (n < length) {
_self.splice(n);
} else if (n > length) {
_self.push.apply(_self, new Array(n - length));
}
} else {
throw new RangeError("Invalid array length");
}
_array.length = n;
return value;
}
});
Object.getOwnPropertyNames(Array.prototype).forEach(function(name) {
if (!(name in _self)) {
Object.defineProperty(_self, name, {
configurable: false,
enumerable: false,
writable: false,
value: Array.prototype[name]
});
}
});
if (items instanceof Array) {
_self.push.apply(_self, items);
}
}
(function testing() {
var x = new ObservableArray(["a", "b", "c", "d"]);
console.log("original array: %o", x.slice());
x.addEventListener("itemadded", function(e) {
console.log("Added %o at index %d.", e.item, e.index);
});
x.addEventListener("itemset", function(e) {
console.log("Set index %d to %o.", e.index, e.item);
});
x.addEventListener("itemremoved", function(e) {
console.log("Removed %o at index %d.", e.item, e.index);
});
console.log("popping and unshifting...");
x.unshift(x.pop());
console.log("updated array: %o", x.slice());
console.log("reversing array...");
console.log("updated array: %o", x.reverse().slice());
console.log("splicing...");
x.splice(1, 2, "x");
console.log("setting index 2...");
x[2] = "foo";
console.log("setting length to 10...");
x.length = 10;
console.log("updated array: %o", x.slice());
console.log("setting length to 2...");
x.length = 2;
console.log("extracting first element via shift()");
x.shift();
console.log("updated array: %o", x.slice());
})();
_x000D_
See Object.defineProperty()
for reference.
That gets us closer but it's still not bullet proof... which brings us to:
A Proxy object offers another solution to the modern browser. It allows you to intercept method calls, accessors, etc. Most importantly, you can do this without even providing an explicit property name... which would allow you to test for an arbitrary, index-based access/assignment. You can even intercept property deletion. Proxies would effectively allow you to inspect a change before deciding to allow it... in addition to handling the change after the fact.
Here's a stripped down sample:
(function() {
if (!("Proxy" in window)) {
console.warn("Your browser doesn't support Proxies.");
return;
}
// our backing array
var array = ["a", "b", "c", "d"];
// a proxy for our array
var proxy = new Proxy(array, {
apply: function(target, thisArg, argumentsList) {
return thisArg[target].apply(this, argumentList);
},
deleteProperty: function(target, property) {
console.log("Deleted %s", property);
return true;
},
set: function(target, property, value, receiver) {
target[property] = value;
console.log("Set %s to %o", property, value);
return true;
}
});
console.log("Set a specific index..");
proxy[0] = "x";
console.log("Add via push()...");
proxy.push("z");
console.log("Add/remove via splice()...");
proxy.splice(1, 3, "y");
console.log("Current state of array: %o", array);
})();
_x000D_
Mozilla recently released the awesome L20n or localization 2.0. In their own words L20n is
an open source, localization-specific scripting language used to process gender, plurals, conjugations, and most of the other quirky elements of natural language.
Their js implementation is on the github L20n repository.
Yes, it is valid to use the anchor tag without a href
attribute.
If the
a
element has nohref
attribute, then the element represents a placeholder for where a link might otherwise have been placed, if it had been relevant, consisting of just the element's contents.
Yes, you can use class
and other attributes, but you can not use target
, download
, rel
, hreflang
, and type
.
The
target
,download
,rel
,hreflang
, andtype
attributes must be omitted if the href attribute is not present.
As for the "Should I?" part, see the first citation: "where a link might otherwise have been placed if it had been relevant". So I would ask "If I had no JavaScript, would I use this tag as a link?". If the answer is yes, then yes, you should use <a>
without href
. If no, then I would still use it, because productivity is more important for me than edge case semantics, but this is just my personal opinion.
Additionally, you should watch out for different behaviour and styling (e.g. no underline, no pointer cursor, not a :link
).
Source: W3C HTML5 Recommendation
In case you want to use numpy here's a way to create an array of all primes not greater than n:
[ i for i in np.arange(2,n+1) if 0 not in np.array([i] * (i-2) ) % np.arange(2,i)]
Another possibility is to use a regular expression:
string a = "this is test";
string pattern = "t";
System.Text.RegularExpressions.Regex ex = new System.Text.RegularExpressions.Regex(pattern);
System.Text.RegularExpressions.MatchCollection m = ex.Matches(a);
MessageBox.Show(m.Count.ToString());
Please convert this into VB.NET.
How about head ?
echo alonglineoftext | head -c 9
Go with this
body {
padding:0px;
margin:0px;
}
Restartable mode (/Z) has to do with a partially-copied file. With this option, should the copy be interrupted while any particular file is partially copied, the next execution of robocopy can pick up where it left off rather than re-copying the entire file.
That option could be useful when copying very large files over a potentially unstable connection.
Backup mode (/B) has to do with how robocopy reads files from the source system. It allows the copying of files on which you might otherwise get an access denied error on either the file itself or while trying to copy the file's attributes/permissions. You do need to be running in an Administrator context or otherwise have backup rights to use this flag.
You could use VirtualPathRoot
property from HttpRequestContext
(request.GetRequestContext().VirtualPathRoot
)
If you are defining your function:
function test() {};
Then, this is equivalent to:
window.test = function() {} /* (in the browser) */
So spyOn(window, 'test')
should work.
If that is not, you should also be able to:
test = jasmine.createSpy();
If none of those are working, something else is going on with your setup.
I don't think your fakeElement
technique works because of what is going on behind the scenes. The original globalMethod still points to the same code. What spying does is proxy it, but only in the context of an object. If you can get your test code to call through the fakeElement it would work, but then you'd be able to give up global fns.
pandas provides two alternatives to Wouter Overmeire's answer which do not require any overriding. One is .loc[.]
with a callable, as in
df_filtered = df.loc[lambda x: x['column'] == value]
the other is .pipe()
, as in
df_filtered = df.pipe(lambda x: x['column'] == value)
It can be useful. Bindings do not always work.
<select id="product" class="form-control" name="product" required
ng-model="issue.productId"
ng-change="getProductVersions()"
ng-options="p.id as p.shortName for p in products"></select>
For example, you fill the options list source model from a REST service. A selected value was known before filling the list, and it was set. After executing the REST request with $http, the list option is done.
But the selected option is not set. For unknown reasons AngularJS in shadow $digest executing does not bind selected as it should be. I have got to use jQuery to set the selected. It`s important! AngularJS, in shadow, adds the prefix to the value of the attr "value" for generated by ng-repeat options. For int it is "number:".
$scope.issue.productId = productId;
function activate() {
$http.get('/product/list')
.then(function (response) {
$scope.products = response.data;
if (productId) {
console.log("" + $("#product option").length);//for clarity
$timeout(function () {
console.log("" + $("#product option").length);//for clarity
$('#product').val('number:'+productId);
}, 200);
}
});
}
We also had this problem when upgrading our system to Revive. After turning of GZIP we found the problem still persisted. Upon further investigation we found the file permissions where not correct after the upgrade. A simple recursive chmod did the trick.
Try using:
test -x filename
or
[ -x filename ]
From the Bash manpage under Conditional Expressions:
-x file True if file exists and is executable.
I think the docs aren't wonderful at exposing how to do this. It has been a supported feature for some time, however, and there are some details in this pull request.
So there are three different ways to do this:
Option A) Create a new session with the profile
dev = boto3.session.Session(profile_name='dev')
Option B) Change the profile of the default session in code
boto3.setup_default_session(profile_name='dev')
Option C) Change the profile of the default session with an environment variable
$ AWS_PROFILE=dev ipython
>>> import boto3
>>> s3dev = boto3.resource('s3')
Try running the entire script through jslint. This may help point you at the cause of the error.
Edit Ok, it's not quite the syntax of the script that's the problem. At least not in a way that jslint can detect.
Having played with your live code at http://ft2.hostei.com/ft.v1/, it looks like there are syntax errors in the generated code that your script puts into an onclick
attribute in the DOM. Most browsers don't do a very good job of reporting errors in JavaScript run via such things (what is the file and line number of a piece of script in the onclick
attribute of a dynamically inserted element?). This is probably why you get a confusing error message in Chrome. The FireFox error message is different, and also doesn't have a useful line number, although FireBug does show the code which causes the problem.
This snippet of code is taken from your edit
function which is in the inline script block of your HTML:
var sub = document.getElementById('submit');
...
sub.setAttribute("onclick", "save(\""+file+"\", document.getElementById('name').value, document.getElementById('text').value");
Note that this sets the onclick
attribute of an element to invalid JavaScript code:
<input type="submit" id="submit" onclick="save("data/wasup.htm", document.getElementById('name').value, document.getElementById('text').value">
The JS is:
save("data/wasup.htm", document.getElementById('name').value, document.getElementById('text').value
Note the missing close paren to finish the call to save
.
As an aside, inserting onclick
attributes is not a very modern or clean way of adding event handlers in JavaScript. Why are you not using the DOM's addEventListener
to simply hook up a function to the element? If you were using something like jQuery, this would be simpler still.
If you are looking at graph analysis in C++ probably the first place to start would be the boost graph library, which implements a number of algorithms including BFS.
EDIT
This previous question on SO will probably help:
how-to-create-a-c-boost-undirected-graph-and-traverse-it-in-depth-first-search
I would recomend to cache the jQuery objects you use more than once. For Instance:
$(document).on("click", ".clickable", function () {
$(this).addClass("grown");
$(this).removeClass("spot");
});
would be:
var doc = $(document);
doc.on('click', '.clickable', function(){
var currentClickedObject = $(this);
currentClickedObject.addClass('grown');
currentClickedObject.removeClass('spot');
});
its actually more code, BUT it is muuuuuuch faster because you dont have to "walk" through the whole jQuery library in order to get the $(this) object.
Or you can just run the following command and you will see all databases of the Redis instance without firing up redis-cli
:
$ redis-cli INFO | grep ^db
db0:keys=1500,expires=2
db1:keys=200000,expires=1
db2:keys=350003,expires=1
In your custom view pager adapter, override those methods in ViewPager
.
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
// Never allow swiping to switch between pages
return false;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// Never allow swiping to switch between pages
return false;
}
And to enable, just return each super
method:
super.onInterceptTouchEvent(event)
and super.onTouchEvent(event)
.
You can give variable names as project files. For instance in you plugin configuration give only one tag as below:-
<projectFile>${projectName}</projectFile>
Then on command line you can pass the project name as parameter:-
mvn [your-command] -DprojectName=[name of project]
Have you tried using the value in MB ?
php_value memory_limit 2048M
Also try editing this value in php.ini
not Apache.
accept
can continuously provide new client connections. However, note that it, and other socket calls are usually blocking. Therefore you have a few options at this point:
Literally none of the answers actually worked for me; the only one that worked for me was (on Linux):
**/bin
(yes without the / in the end)
git version 2.18.0
The most of the above given examples create a problem when a year has 53 weeks (like 2020). So every fourth year you will experience a week difference. This code does not:
$thisYear = "2020";
$thisDate = "2020-04-24"; //or any other custom date
$weeknr = date("W", strtotime($thisDate)); //when you want the weeknumber of a specific week, or just enter the weeknumber yourself
$tempDatum = new DateTime();
$tempDatum->setISODate($thisYear, $weeknr);
$tempDatum_start = $tempDatum->format('Y-m-d');
$tempDatum->setISODate($thisYear, $weeknr, 7);
$tempDatum_end = $tempDatum->format('Y-m-d');
echo $tempDatum_start //will output the date of monday
echo $tempDatum_end // will output the date of sunday
Till yesterday I was able to connect to phpMyAdmin, but today I started getting this error:
2002-no-connection-could-be-made-because-the-target-machine-actively-refused
None of the answers here really helped me fix the problem, what helped me is shared below:
I looked at the mysql logs.[C:\wamp\logs\mysql.log]
It said
2015-09-18 01:16:30 5920 [Note] Plugin 'FEDERATED' is disabled.
2015-09-18 01:16:30 5920 [Note] InnoDB: Using atomics to ref count buffer pool pages
2015-09-18 01:16:30 5920 [Note] InnoDB: The InnoDB memory heap is disabled
2015-09-18 01:16:30 5920 [Note] InnoDB: Mutexes and rw_locks use Windows interlocked functions
2015-09-18 01:16:30 5920 [Note] InnoDB: Compressed tables use zlib 1.2.3
2015-09-18 01:16:30 5920 [Note] InnoDB: Not using CPU crc32 instructions
2015-09-18 01:16:30 5920 [Note] InnoDB: Initializing buffer pool, size = 128.0M
2015-09-18 01:16:30 5920 [Note] InnoDB: Completed initialization of buffer pool
2015-09-18 01:16:30 5920 [Note] InnoDB: Highest supported file format is Barracuda.
2015-09-18 01:16:30 5920 [Note] InnoDB: The log sequence numbers 1765410 and 1765410 in ibdata files do not match the log sequence number 2058233 in the ib_logfiles!
2015-09-18 01:16:30 5920 [Note] InnoDB: Database was not shutdown normally!
2015-09-18 01:16:30 5920 [Note] InnoDB: Starting crash recovery.
2015-09-18 01:16:30 5920 [Note] InnoDB: Reading tablespace information from the .ibd files...
2015-09-18 01:16:30 5920 [ERROR] InnoDB: Attempted to open a previously opened tablespace. Previous tablespace harley/login_confirm uses space ID: 6 at filepath: .\harley\login_confirm.ibd. Cannot open tablespace testdb/testtable which uses space ID: 6 at filepath: .\testdb\testtable.ibd
InnoDB: Error: could not open single-table tablespace file .\testdb\testtable.ibd
InnoDB: We do not continue the crash recovery, because the table may become
InnoDB: corrupt if we cannot apply the log records in the InnoDB log to it.
InnoDB: To fix the problem and start mysqld:
InnoDB: 1) If there is a permission problem in the file and mysqld cannot
InnoDB: open the file, you should modify the permissions.
InnoDB: 2) If the table is not needed, or you can restore it from a backup,
InnoDB: then you can remove the .ibd file, and InnoDB will do a normal
InnoDB: crash recovery and ignore that table.
InnoDB: 3) If the file system or the disk is broken, and you cannot remove
InnoDB: the .ibd file, you can set innodb_force_recovery > 0 in my.cnf
InnoDB: and force InnoDB to continue crash recovery here.
I got the clue that this guy is creating a problem - InnoDB: Error: could not open single-table tablespace file .\testdb\testtable.ibd
and this line 2015-09-18 01:16:30 5920 [Note] InnoDB: Database was not shutdown normally!
hmmm, For me the testdb was just a test-db! hence I decided to delete this file inside C:\wamp\bin\mysql\mysql5.6.17\data\testdb
and restarted all services, and went to phpMyAdmin, and this time no issues, phpMyAdmin opened :)
You may have imported,
project/controllers/base
inside the
project/controllers/routes
You have already imported before. That's not supported.
Although purely from engineering perspective, indexed views sound like something everybody could use to improve performance but the real life scenario is very different. I have been unsuccessful is using indexed views where I most need them because of too many restrictions on what can be indexed and what cannot.
If you have outer joins in the views, they cannot be used. Also, common table expressions are not allowed... In fact if you have any ordering in subselects or derived tables (such as with partition by clause), you are out of luck too.
That leaves only very simple scenarios to be utilizing indexed views, something in my opinion can be optimized by creating proper indexes on underlying tables anyway.
I will be thrilled to hear some real life scenarios where people have actually used indexed views to their benefit and could not have done without them
This works, as long as you remove the height attribute from the table.
<table id="content" border="0px" cellspacing="0px" cellpadding="0px">
<tr><td height='9px' bgcolor="#990000">Upper</td></tr>
<tr><td height='100px' bgcolor="#990099">Lower</td></tr>
</table>
There is no structure in numpy that allows you to append more data later.
Instead, numpy puts all of your data into a contiguous chunk of numbers (basically; a C array), and any resize requires allocating a new chunk of memory to hold it. Numpy's speed comes from being able to keep all the data in a numpy array in the same chunk of memory; e.g. mathematical operations can be parallelized for speed and you get less cache misses.
So you will have two kinds of solutions:
images = []
for i in range(100):
new_image = # pull image from somewhere
images.append(new_image)
images = np.stack(images, axis=3)
Note that there is no need to expand the dimensions of the individual image arrays first, nor do you need to know how many images you expect ahead of time.
None of these worked for me. I did find the solution in another stackoverflow question. I'll add it here for easy reference:
You need to make a reference, so it will be copied in den application path. Because later it will be referenced in runtime. So you don't need to copy any files.
private volatile Type _dependency;
public MyClass()
{
_dependency = typeof(System.Data.Entity.SqlServer.SqlProviderServices);
}
You don't need the assignment, list.append(x)
will always append x
to a
and therefore there's no need te redefine a
.
a = []
for i in range(5):
a.append(i)
print(a)
is all you need. This works because list
s are mutable.
Also see the docs on data structures.
Based on what you all shared I was able to put this together:
#!/usr/bin/env bash
VAR1="192.168.1.20 192.168.1.126 192.168.1.36"
for a in $VAR1; do { ssh -t -t $a -l Administrator "sudo softwareupdate -l"; } & done;
WAITPIDS="$WAITPIDS "$!;...; wait $WAITPIDS
echo "Script has finished"
Exit 1
This lists all the updates on the mac on three machines at once. Later on I used it to perform a software update for all machines when i CAT my ipaddress.txt
After a bit of time (and more searching), I found this blog entry by Jomo Fisher.
One of the recent problems we’ve seen is that, because of the support for side-by-side runtimes, .NET 4.0 has changed the way that it binds to older mixed-mode assemblies. These assemblies are, for example, those that are compiled from C++\CLI. Currently available DirectX assemblies are mixed mode. If you see a message like this then you know you have run into the issue:
Mixed mode assembly is built against version 'v1.1.4322' of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information.
[Snip]
The good news for applications is that you have the option of falling back to .NET 2.0 era binding for these assemblies by setting an app.config flag like so:
<startup useLegacyV2RuntimeActivationPolicy="true"> <supportedRuntime version="v4.0"/> </startup>
So it looks like the way the runtime loads mixed-mode assemblies has changed. I can't find any details about this change, or why it was done. But the useLegacyV2RuntimeActivationPolicy
attribute reverts back to CLR 2.0 loading.
Here's a demo. Even works in IE7:
http://james.padolsey.com/demos/grayscale/
and
http://james.padolsey.com/javascript/grayscaling-in-non-ie-browsers/