Well, you pretty much gave yourself the answer. In your CSS give the containing element a min-width. If you have to support IE6 you can use the min-width-trick:
#container {
min-width:800px;
width: auto !important;
width:800px;
}
That will effectively give you 800px min-width in IE6 and any up-to-date browsers.
First off, I know the addEventListener
method has been mentioned in the comments above, but I didn't see any code. Since it's the preferred approach, here it is:
window.addEventListener('resize', function(event){
// do stuff here
});
.pom
dependency
scope
can contain:
compile
- available at Compile-time and Run-timeprovided
- available at Compile-time. (this dependency should be provided by outer container like OS...)runtime
- available at Run-timetest
- test compilation and run timesystem
- is similar to provided
but exposes <systemPath>path/some.jar</systemPath>
to point on .jar
import
- is available from Maven v2.0.9 for <type>pom</type>
and it should be replaced by effective dependency from this file <dependencyManagement/>
On Android prior to 4.2, go to Google Settings, tap Verify apps and uncheck the option Verify apps.
On Android 4.2+, uncheck the option Settings > Security > Verify apps and/or Settings > Developer options > Verify apps over USB.
If you get this issue, then either
As drewm himself said this is due to the subsequent redirect after the POST to the script has in fact succeeded. (I might have added this as a comment to his answer but you need 50 reputation to comment and I'm new round here - daft rule IMHO)
BUT it also applies if you're trying to redirect to a page, not just a directory - at least it did for me. I was trying to redirect to /thankyou.html. What fixes this is using an absolute URL, i.e. http://example.com/thankyou.html
I also had the same problem, I tried many different command lines, this one worked for me:
Try:
conda install py-xgboost
That's what I got:
Collecting package metadata: done
Solving environment: done
## Package Plan ##
environment location: /home/simplonco/anaconda3
added / updated specs:
- py-xgboost
The following packages will be downloaded:
package | build
---------------------------|-----------------
_py-xgboost-mutex-2.0 | cpu_0 9 KB
ca-certificates-2019.1.23 | 0 126 KB
certifi-2018.11.29 | py37_0 146 KB
conda-4.6.2 | py37_0 1.7 MB
libxgboost-0.80 | he6710b0_0 3.7 MB
mkl-2019.1 | 144 204.6 MB
mkl_fft-1.0.10 | py37ha843d7b_0 169 KB
mkl_random-1.0.2 | py37hd81dba3_0 405 KB
numpy-1.15.4 | py37h7e9f1db_0 47 KB
numpy-base-1.15.4 | py37hde5b4d6_0 4.2 MB
py-xgboost-0.80 | py37he6710b0_0 1.7 MB
scikit-learn-0.20.2 | py37hd81dba3_0 5.7 MB
scipy-1.2.0 | py37h7c811a0_0 17.7 MB
------------------------------------------------------------
Total: 240.0 MB
The following NEW packages will be INSTALLED:
_py-xgboost-mutex pkgs/main/linux-64::_py-xgboost-mutex-2.0-cpu_0
libxgboost pkgs/main/linux-64::libxgboost-0.80-he6710b0_0
py-xgboost pkgs/main/linux-64::py-xgboost-0.80-py37he6710b0_0
The following packages will be UPDATED:
ca-certificates anaconda::ca-certificates-2018.12.5-0 --> pkgs/main::ca-certificates-2019.1.23-0
mkl 2019.0-118 --> 2019.1-144
mkl_fft 1.0.4-py37h4414c95_1 --> 1.0.10-py37ha843d7b_0
mkl_random 1.0.1-py37h4414c95_1 --> 1.0.2-py37hd81dba3_0
numpy 1.15.1-py37h1d66e8a_0 --> 1.15.4-py37h7e9f1db_0
numpy-base 1.15.1-py37h81de0dd_0 --> 1.15.4-py37hde5b4d6_0
scikit-learn 0.19.2-py37h4989274_0 --> 0.20.2-py37hd81dba3_0
scipy 1.1.0-py37hfa4b5c9_1 --> 1.2.0-py37h7c811a0_0
The following packages will be SUPERSEDED by a higher-priority channel:
certifi anaconda --> pkgs/main
conda anaconda --> pkgs/main
openssl anaconda::openssl-1.1.1-h7b6447c_0 --> pkgs/main::openssl-1.1.1a-h7b6447c_0
Proceed ([y]/n)? y
Downloading and Extracting Packages
libxgboost-0.80 | 3.7 MB | ##################################### | 100%
mkl_random-1.0.2 | 405 KB | ##################################### | 100%
certifi-2018.11.29 | 146 KB | ##################################### | 100%
ca-certificates-2019 | 126 KB | ##################################### | 100%
conda-4.6.2 | 1.7 MB | ##################################### | 100%
mkl-2019.1 | 204.6 MB | ##################################### | 100%
mkl_fft-1.0.10 | 169 KB | ##################################### | 100%
numpy-1.15.4 | 47 KB | ##################################### | 100%
scipy-1.2.0 | 17.7 MB | ##################################### | 100%
scikit-learn-0.20.2 | 5.7 MB | ##################################### | 100%
py-xgboost-0.80 | 1.7 MB | ##################################### | 100%
_py-xgboost-mutex-2. | 9 KB | ##################################### | 100%
numpy-base-1.15.4 | 4.2 MB | ##################################### | 100%
Preparing transaction: done
Verifying transaction: done
Executing transaction: done
Can I control the HTTP headers sent by window.open (cross browser)?
No
If not, can I somehow window.open a page that then issues my request with custom headers inside its popped-up window?
I need some cunning hacks...
It might help if you described the problem instead of asking if possible solutions would work.
from string import rstrip
with open('bvc.txt') as f:
alist = map(rstrip, f)
Nota Bene: rstrip()
removes the whitespaces, that is to say : \f
, \n
, \r
, \t
, \v
, \x
and blank ,
but I suppose you're only interested to keep the significant characters in the lines. Then, mere map(strip, f)
will fit better, removing the heading whitespaces too.
If you really want to eliminate only the NL \n
and RF \r
symbols, do:
with open('bvc.txt') as f:
alist = f.read().splitlines()
splitlines() without argument passed doesn't keep the NL and RF symbols (Windows records the files with NLRF at the end of lines, at least on my machine) but keeps the other whitespaces, notably the blanks and tabs.
.
with open('bvc.txt') as f:
alist = f.read().splitlines(True)
has the same effect as
with open('bvc.txt') as f:
alist = f.readlines()
that is to say the NL and RF are kept
FragmentActivity
is part of the support library, while Activity
is the framework's default class. They are functionally equivalent.
You should always use FragmentActivity
and android.support.v4.app.Fragment
instead of the platform default Activity
and android.app.Fragment
classes. Using the platform defaults mean that you are relying on whatever implementation of fragments is used in the device you are running on. These are often multiple years old, and contain bugs that have since been fixed in the support library.
In both your examples, local variables of Object*
type are allocated on the stack. The compiler is free to produce the same code from both snippets if there is no way for your program to detect a difference.
The memory area for global variables is the same as the memory area for static variables - it's neither on the stack nor on the heap. You can place variables in that area by declaring them static
inside the function. The consequence of doing so is that the instance becomes shared among concurrent invocations of your function, so you need to carefully consider synchronization when you use statics.
Here is a link to a discussion of the memory layout of a running C program.
Did you handwrite the program and then scan it into the computer? That is what is implied by "helloworld.png". If that is the case, you need to be aware that the C++ standard (even in its newest edition) does not require the presence of optical character recognition, and unfortunately it is not included as an optional feature in any current compiler.
You may want to consider transposing the graphics to a textual format. Any plain-text editor may be used; the use of a word processor, while capable of generating a pretty printout, will most likely result in the same error that you get while trying to scan.
If you are truly adventurous, you may attempt to write your code into a word processor. Print it, preferably using a font like OCR-A. Then, take your printout and scan it back in. The scan can then be run through a third-party OCR package to generate a text form. The text form may then be compiled using one of many standard compilers.
Beware, however, of the great cost of paper that this will incur during the debugging phase.
And there is:
function character_count(string, char, ptr = 0, count = 0) {
while (ptr = string.indexOf(char, ptr) + 1) {count ++}
return count
}
Works with integers too!
5 Jan 2021: link update thanks to @Sadap's comment.
Kind of a corollary answer: the people on this site have taken the time to make tables of macros defined for every OS/compiler pair.
For example, you can see that _WIN32
is NOT defined on Windows with Cygwin (POSIX), while it IS defined for compilation on Windows, Cygwin (non-POSIX), and MinGW with every available compiler (Clang, GNU, Intel, etc.).
Anyway, I found the tables quite informative and thought I'd share here.
Warning This method will not work beyond 5.0, it was a quite dated entry.
You can use the following code to enable, disable and query the wifi direct state programatically.
package com.kusmezer.androidhelper.networking;
import java.lang.reflect.Method;
import com.google.common.base.Preconditions;
import android.content.Context;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.util.Log;
public final class WifiApManager {
private static final int WIFI_AP_STATE_FAILED = 4;
private final WifiManager mWifiManager;
private final String TAG = "Wifi Access Manager";
private Method wifiControlMethod;
private Method wifiApConfigurationMethod;
private Method wifiApState;
public WifiApManager(Context context) throws SecurityException, NoSuchMethodException {
context = Preconditions.checkNotNull(context);
mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
wifiControlMethod = mWifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class,boolean.class);
wifiApConfigurationMethod = mWifiManager.getClass().getMethod("getWifiApConfiguration",null);
wifiApState = mWifiManager.getClass().getMethod("getWifiApState");
}
public boolean setWifiApState(WifiConfiguration config, boolean enabled) {
config = Preconditions.checkNotNull(config);
try {
if (enabled) {
mWifiManager.setWifiEnabled(!enabled);
}
return (Boolean) wifiControlMethod.invoke(mWifiManager, config, enabled);
} catch (Exception e) {
Log.e(TAG, "", e);
return false;
}
}
public WifiConfiguration getWifiApConfiguration()
{
try{
return (WifiConfiguration)wifiApConfigurationMethod.invoke(mWifiManager, null);
}
catch(Exception e)
{
return null;
}
}
public int getWifiApState() {
try {
return (Integer)wifiApState.invoke(mWifiManager);
} catch (Exception e) {
Log.e(TAG, "", e);
return WIFI_AP_STATE_FAILED;
}
}
}
In your example there is no big difference between str -> str
and Function.identity()
since internally it is simply t->t
.
But sometimes we can't use Function.identity
because we can't use a Function
. Take a look here:
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
this will compile fine
int[] arrayOK = list.stream().mapToInt(i -> i).toArray();
but if you try to compile
int[] arrayProblem = list.stream().mapToInt(Function.identity()).toArray();
you will get compilation error since mapToInt
expects ToIntFunction
, which is not related to Function
. Also ToIntFunction
doesn't have identity()
method.
$.ajax({_x000D_
url: "https://geolocation-db.com/jsonp",_x000D_
jsonpCallback: "callback",_x000D_
dataType: "jsonp",_x000D_
success: function(location) {_x000D_
$('#country').html(location.country_name);_x000D_
$('#state').html(location.state);_x000D_
$('#city').html(location.city);_x000D_
$('#latitude').html(location.latitude);_x000D_
$('#longitude').html(location.longitude);_x000D_
$('#ip').html(location.IPv4);_x000D_
}_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div>Country: <span id="country"></span></div>_x000D_
<div>State: <span id="state"></span></div>_x000D_
<div>City: <span id="city"></span></div>_x000D_
<div>Latitude: <span id="latitude"></span></div>_x000D_
<div>Longitude: <span id="longitude"></span></div>_x000D_
<div>IP: <span id="ip"></span></div>
_x000D_
Using html5 geolocation requires user permission. In case you don't want this, go for an external locator like https://geolocation-db.com IPv6 is supported. No restrictions and unlimited requests allowed.
Example
For a pure javascript example, without using jQuery, check out this answer.
This is yet another way of cloning the model instance:
d = Foo.objects.filter(pk=1).values().first()
d.update({'id': None})
duplicate = Foo.objects.create(**d)
As a type that contains children, I'm using:
type ChildrenContainer = Pick<JSX.IntrinsicElements["div"], "children">
This children container type is generic enough to support all the different cases and also aligned with the ReactJS API.
So, for your example it would be something like:
const layout = ({ children }: ChildrenContainer) => (
<Aux>
<div>Toolbar, SideDrawer, Backdrop</div>
<main>
{children}
</main>
<Aux/>
)
If you can use extension methods, this will do it in a safe way regardless of string length:
public static string Right(this string text, int maxLength)
{
if (string.IsNullOrEmpty(text) || maxLength <= 0)
{
return string.Empty;
}
if (maxLength < text.Length)
{
return text.Substring(text.Length - maxLength);
}
return text;
}
And to use it:
string sub = input.Right(5);
<iframe src="https://maps.google.com/maps?q='+YOUR_LAT+','+YOUR_LON+'&hl=en&z=14&output=embed" width="100%" height="400" frameborder="0" style="border:0" allowfullscreen></iframe>
put your replace lattitude,longitude values on YOUR_LAT,YOUR_LON respectively. hl parameter for setting language on map, z for zoomlevel;
let a = {};_x000D_
let b = {};_x000D_
_x000D_
a.prop1 = 2;_x000D_
a.prop2 = { prop3: 2 };_x000D_
_x000D_
b.prop1 = 2;_x000D_
b.prop2 = { prop3: 3 };_x000D_
_x000D_
JSON.stringify(a) === JSON.stringify(b);_x000D_
// false_x000D_
b.prop2 = { prop3: 2};_x000D_
_x000D_
JSON.stringify(a) === JSON.stringify(b);_x000D_
// true
_x000D_
The easiest way to use PhantomJS in python is via Selenium. The simplest installation method is
npm -g install phantomjs-prebuilt
After installation, you may use phantom as simple as:
from selenium import webdriver
driver = webdriver.PhantomJS() # or add to your PATH
driver.set_window_size(1024, 768) # optional
driver.get('https://google.com/')
driver.save_screenshot('screen.png') # save a screenshot to disk
sbtn = driver.find_element_by_css_selector('button.gbqfba')
sbtn.click()
If your system path environment variable isn't set correctly, you'll need to specify the exact path as an argument to webdriver.PhantomJS()
. Replace this:
driver = webdriver.PhantomJS() # or add to your PATH
... with the following:
driver = webdriver.PhantomJS(executable_path='/usr/local/lib/node_modules/phantomjs/lib/phantom/bin/phantomjs')
References:
You can accomplish this as follows:
if a_string.isdigit():
do_this()
else:
do_that()
https://docs.python.org/2/library/stdtypes.html#str.isdigit
Using .isdigit()
also means not having to resort to exception handling (try/except) in cases where you need to use list comprehension (try/except is not possible inside a list comprehension).
I have got the solution for my query:
i have done something like this:
cell.innerHTML="<img height=40 width=40 alt='' src='<%=request.getContextPath()%>/writeImage.htm?' onerror='onImgError(this);' onLoad='setDefaultImage(this);'>"
function setDefaultImage(source){
var badImg = new Image();
badImg.src = "video.png";
var cpyImg = new Image();
cpyImg.src = source.src;
if(!cpyImg.width)
{
source.src = badImg.src;
}
}
function onImgError(source){
source.src = "video.png";
source.onerror = "";
return true;
}
This way it's working in all browsers.
Intel® VTune™ Performance Analyzer for quick sampling
Use DateTimeFormat
:
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss");
DateTime dt = formatter.parseDateTime(string);
I was having a problem building notifications (only developing for Android 4.0+). This link showed me exactly what I was doing wrong and says the following:
Required notification contents
A Notification object must contain the following:
A small icon, set by setSmallIcon()
A title, set by setContentTitle()
Detail text, set by setContentText()
Basically I was missing one of these. Just as a basis for troubleshooting with this, make sure you have all of these at the very least. Hopefully this will save someone else a headache.
So to add the string hello
to a list as individual characters, try this:
newlist = []
newlist[:0] = 'hello'
print (newlist)
['h','e','l','l','o']
However, it is easier to do this:
splitlist = list(newlist)
print (splitlist)
if x
is numeric, then add scale_x_continuous()
; if x
is character/factor, then add scale_x_discrete()
. This might solve your problem.
Clicking a radio button should trigger an event that either:
self.props.selectionChanged(...)
In the first case, the change is state will trigger a re-render and you can do
<td>chosen site name {this.state.chosenSiteName} </td>
in the second case, the source of the callback will update things to ensure that down the line, your SearchResult instance will have chosenSiteName and chosenAddress set in it's props.
Using only the portable JAVA API. http://www.oracle.com/technetwork/articles/java/json-1973242.html
try (JsonReader reader = Json.createReader(new StringReader(yourJSONresponse))) {
JsonArray arr = reader.readArray();
List<String> l = arr.getValuesAs(JsonObject.class)
.stream().map(o -> o.getString("name")).collect(Collectors.toList());
}
In my case i removed
Restart=always
added
tty: true
And executed the below command to open shell (daemon process, because docker reads the compose file and stops the container once it reaches the last line of the file).
docker-compose up -d
To all who have faced this issue/ will face it in the future:
Click on Build menu -> Select Build Variant -> restore to 'debug'
Outcomment on debuggable in module:app /* debug { debuggable true }*/
Go to Build menu -> generate signed apk -> .... -> build it
There are many ways to get a page from the command line... but it also depends if you want the code source or the page itself:
If you need the code source:
with curl:
curl $url
with wget:
wget -O - $url
but if you want to get what you can see with a browser, lynx can be useful:
lynx -dump $url
I think you can find so many solutions for this little problem, maybe you should read all man pages for those commands. And don't forget to replace $url
by your URL :)
Good luck :)
The double \ should work for Windows, but you still need to take care of the folders you mention in your path. All of them (exept the filename) must exist. otherwise you will get an error.
If you just want to print the substrings ...
char s[] = "THESTRINGHASNOSPACES";
size_t i, slen = strlen(s);
for (i = 0; i < slen; i += 4) {
printf("%.4s\n", s + i);
}
// example:
// checkEach(1000, () => {
// if(!canIDoWorkNow()) {
// return true // try again after 1 second
// }
//
// doWork()
// })
export function checkEach(milliseconds, fn) {
const timer = setInterval(
() => {
try {
const retry = fn()
if (retry !== true) {
clearInterval(timer)
}
} catch (e) {
clearInterval(timer)
throw e
}
},
milliseconds
)
}
You do not need to use formatted="false"
in your XML. You just need to use fully qualified string format markers - %[POSITION]$[TYPE]
(where [POSITION]
is the attribute position and [TYPE]
is the variable type), rather than the short versions, for example %s
or %d
.
Quote from Android Docs: String Formatting and Styling:
<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>
In this example, the format string has two arguments:
%1$s
is a string and%2$d
is a decimal integer. You can format the string with arguments from your application like this:Resources res = getResources(); String text = res.getString(R.string.welcome_messages, username, mailCount);
simple google search turned up this:
If the data is actually an HTML page and has NOT been created by ASP, PHP, or some other scripting language, and you are using Internet Explorer 6, and you have Excel installed on your computer, simply right-click on the page and look through the menu. You should see "Export to Microsoft Excel." If all these conditions are true, click on the menu item and after a few prompts it will be imported to Excel.
if you can't do that, he gives an alternate "drag-and-drop" method:
Try redirecting the output to Out-Null. Like so,
$key = & 'gpg' --decrypt "secret.gpg" --quiet --no-verbose | out-null
It helps to group multiple statements into a single one so that a function-like macro can actually be used as a function. Suppose you have:
#define FOO(n) foo(n);bar(n)
and you do:
void foobar(int n) {
if (n)
FOO(n);
}
then this expands to:
void foobar(int n) {
if (n)
foo(n);bar(n);
}
Notice that the second call bar(n)
is not part of the if
statement anymore.
Wrap both into do { } while(0)
, and you can also use the macro in an if
statement.
Generate random colors;
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
and call it for each record;
function getRandomColorEachEmployee(count) {
var data =[];
for (var i = 0; i < count; i++) {
data.push(getRandomColor());
}
return data;
}
finally set colors;
var data = {
labels: jsonData.employees, // your labels
datasets: [{
data: jsonData.approvedRatios, // your data
backgroundColor: getRandomColorEachEmployee(jsonData.employees.length)
}]
};
The accepted answer duplicates the first row if the frame only contains a single row. If that's a concern
df[0::len(df)-1 if len(df) > 1 else 1]
works even for single row-dataframes.
Example: For the following dataframe this will not create a duplicate:
df = pd.DataFrame({'a': [1], 'b':['a']})
df2 = df[0::len(df)-1 if len(df) > 1 else 1]
print df2
a b
0 1 a
whereas this does:
df3 = df.iloc[[0, -1]]
print df3
a b
0 1 a
0 1 a
because the single row is the first AND last row at the same time.
The best practice for this situation. Use RETURNING … INTO
.
INSERT INTO teams VALUES (...) RETURNING id INTO last_id;
Note this is for PLPGSQL
I doubt I'd use it in a mission-critical system, but Derby has always been very interesting to me.
Even more useful, if you have multiple parameters you can access any/all of them with:
_mock.Setup(x => x.DoSomething(It.IsAny<string>(),It.IsAny<string>(),It.IsAny<string>())
.Returns((string a, string b, string c) => string.Concat(a,b,c));
You always need to reference all the arguments, to match the method's signature, even if you're only going to use one of them.
Amazon provides a policy generator tool:
https://awspolicygen.s3.amazonaws.com/policygen.html
After that, you can enter the policy requirements for the bucket on the AWS console:
tools: context = "activity name"
it won't be packaged into the apk
.Only ADT
Layout Editor in your current Layout file set corresponding rendering context, show your current Layout in rendering the context is the activity name corresponds to the activity, if the activity in the manifest
file set a Theme, then ADT
Layout Editor will render your current Layout according to the Theme.Means that if you set the MainActivity
set a Theme. The Light (the other), then you see in visual layout manager o background control of what should be the Theme. The Light looks like.Only to show you what you see is what you get results.
Some people see will understand some, some people see the also don't know, I'll add a few words of explanation:
Take a simple
tools:text
, for example, some more image, convenient to further understand thetools:context
<TextView
android:id="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="sample name1" />
<TextView
android:id="@+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:text="sample name2" />
TextView
1 adopted theandroid: text
, and use thetools:text
in theTextView
2, on the right side of the Layout editor will display thesample name1
, thesample name2
two font, if after you run the code to compile, generatedapk
, terminal display only thesample name1
, does not show thesample name2
the words. You can try to run, see how the effect.
1.The tools: context = "activity name"
it won't be packaged into the apk
(understanding: the equivalent of this is commented, the compiled no effect.)
2.Only ADT
Layout Editor (i.e., for the above icon on the right side of the simulator) in the current Layout file set corresponding rendering context, the Layout of the current XML in rendering the context is the activity name corresponds to the activity, if the activity in the manifest file set a Theme, then ADT
Layout Editor will render your current Layout according to the Theme.Means that if you set the MainActivity
set a Theme. The Light can also be (other).(understand: you added tools: context = "activity name"
, the XML layout is rendering specified activity, establishes a Theme in the manifest file, pictured above right simulator Theme style will also follow changes corresponding to the Theme.)
To sum up, these properties mainly aimed at above the right tools, the simulator debugging time display status, and compile doesn't work,
Use the built in function zip
property_asel = [a for (a, truth) in zip(property_a, good_objects) if truth]
Just looking at the new features of 2.7. There is now a function in the itertools module which is similar to the above code.
http://docs.python.org/library/itertools.html#itertools.compress
itertools.compress('ABCDEF', [1,0,1,0,1,1]) =>
A, C, E, F
declare @cur cursor
declare @idx int
declare @Approval_No varchar(50)
declare @ReqNo varchar(100)
declare @M_Id varchar(100)
declare @Mail_ID varchar(100)
declare @temp table
(
val varchar(100)
)
declare @temp2 table
(
appno varchar(100),
mailid varchar(100),
userod varchar(100)
)
declare @slice varchar(8000)
declare @String varchar(100)
--set @String = '1200096,1200095,1200094,1200093,1200092,1200092'
set @String = '20131'
select @idx = 1
if len(@String)<1 or @String is null return
while @idx!= 0
begin
set @idx = charindex(',',@String)
if @idx!=0
set @slice = left(@String,@idx - 1)
else
set @slice = @String
--select @slice
insert into @temp values(@slice)
set @String = right(@String,len(@String) - @idx)
if len(@String) = 0 break
end
-- select distinct(val) from @temp
SET @cur = CURSOR FOR select distinct(val) from @temp
--open cursor
OPEN @cur
--fetchng id into variable
FETCH NEXT
FROM @cur into @Approval_No
--
--loop still the end
while @@FETCH_STATUS = 0
BEGIN
select distinct(Approval_Sr_No) as asd, @ReqNo=Approval_Sr_No,@M_Id=AM_ID,@Mail_ID=Mail_ID from WFMS_PRAO,WFMS_USERMASTER where WFMS_PRAO.AM_ID=WFMS_USERMASTER.User_ID
and Approval_Sr_No=@Approval_No
insert into @temp2 values(@ReqNo,@M_Id,@Mail_ID)
FETCH NEXT
FROM @cur into @Approval_No
end
--close cursor
CLOSE @cur
select * from @tem
I wanted a dynamic version for select multiple that would display what is selected to the right (wish I'd read on and seen $(this).find
... earlier):
<script type="text/javascript">
$(document).ready(function(){
$("select[showChoices]").each(function(){
$(this).after("<span id='spn"+$(this).attr('id')+"' style='border:1px solid black;width:100px;float:left;white-space:nowrap;'> </span>");
doShowSelected($(this).attr('id'));//shows initial selections
}).change(function(){
doShowSelected($(this).attr('id'));//as user makes new selections
});
});
function doShowSelected(inId){
var aryVals=$("#"+inId).val();
var selText="";
for(var i=0; i<aryVals.length; i++){
var o="#"+inId+" option[value='"+aryVals[i]+"']";
selText+=$(o).text()+"<br>";
}
$("#spn"+inId).html(selText);
}
</script>
<select style="float:left;" multiple="true" id="mySelect" name="mySelect" showChoices="true">
<option selected="selected" value=1>opt 1</option>
<option selected="selected" value=2>opt 2</option>
<option value=3>opt 3</option>
<option value=4>opt 4</option>
</select>
In the menu, go to RUN > services.msc
and hit enter to get the services window and check for the IIS ADMIN service. If it is not present, then reinstall IIS using your windows CD.
... and Trick #3 Multiline entries in an Xtable
Generate some more data
moredata<-data.frame(Nominal=c(1:5), n=rep(5,5),
MeanLinBias=signif(rnorm(5, mean=0, sd=10), digits=4),
LinCI=paste("(",signif(rnorm(5,mean=-2, sd=5), digits=4),
", ", signif(rnorm(5, mean=2, sd=5), digits=4),")",sep=""),
MeanQuadBias=signif(rnorm(5, mean=0, sd=10), digits=4),
QuadCI=paste("(",signif(rnorm(5,mean=-2, sd=5), digits=4),
", ", signif(rnorm(5, mean=2, sd=5), digits=4),")",sep=""))
names(moredata)<-c("Nominal", "n","Linear Model \nBias","Linear \nCI", "Quadratic Model \nBias", "Quadratic \nCI")
Now produce our xtable, using the sanitize function to replace column names with the correct Latex newline commands (including double backslashes so R is happy)
<<label=multilinetable, results=tex, echo=FALSE>>=
foo<-xtable(moredata)
align(foo) <- c( rep('c',3),'p{1.8in}','p{2in}','p{1.8in}','p{2in}' )
print(foo,
floating=FALSE,
include.rownames=FALSE,
sanitize.text.function = function(str) {
str<-gsub("\n","\\\\", str, fixed=TRUE)
return(str)
},
sanitize.colnames.function = function(str) {
str<-c("Nominal", "n","\\centering Linear Model\\\\ \\% Bias","\\centering Linear \\\\ 95\\%CI", "\\centering Quadratic Model\\\\ \\%Bias", "\\centering Quadratic \\\\ 95\\%CI \\tabularnewline")
return(str)
})
@
(although this isn't perfect, as we need \tabularnewline so the table is formatted correctly, and Xtable still puts in a final \, so we end up with a blank line below the table header.)
As mentioned in this comment, the standard suggestions for re-ordering columns in a data.frame
are generally cumbersome and error-prone, especially if you have a lot of columns.
This function allows to re-arrange columns by position: specify a variable name and the desired position, and don't worry about the other columns.
##arrange df vars by position
##'vars' must be a named vector, e.g. c("var.name"=1)
arrange.vars <- function(data, vars){
##stop if not a data.frame (but should work for matrices as well)
stopifnot(is.data.frame(data))
##sort out inputs
data.nms <- names(data)
var.nr <- length(data.nms)
var.nms <- names(vars)
var.pos <- vars
##sanity checks
stopifnot( !any(duplicated(var.nms)),
!any(duplicated(var.pos)) )
stopifnot( is.character(var.nms),
is.numeric(var.pos) )
stopifnot( all(var.nms %in% data.nms) )
stopifnot( all(var.pos > 0),
all(var.pos <= var.nr) )
##prepare output
out.vec <- character(var.nr)
out.vec[var.pos] <- var.nms
out.vec[-var.pos] <- data.nms[ !(data.nms %in% var.nms) ]
stopifnot( length(out.vec)==var.nr )
##re-arrange vars by position
data <- data[ , out.vec]
return(data)
}
Now the OP's request becomes as simple as this:
table <- data.frame(Time=c(1,2), In=c(2,3), Out=c(3,4), Files=c(4,5))
table
## Time In Out Files
##1 1 2 3 4
##2 2 3 4 5
arrange.vars(table, c("Out"=2))
## Time Out In Files
##1 1 3 2 4
##2 2 4 3 5
To additionally swap Time
and Files
columns you can do this:
arrange.vars(table, c("Out"=2, "Files"=1, "Time"=4))
## Files Out In Time
##1 4 3 2 1
##2 5 4 3 2
In my case, heredoc caused the issue. There is no problem with PHP version 7.3 up. Howerver, it error with PHP 7.0.33 if you use heredoc with space.
My example code
$rexpenditure = <<<Expenditure
<tr>
<td>$row->payment_referencenumber</td>
<td>$row->payment_requestdate</td>
<td>$row->payment_description</td>
<td>$row->payment_fundingsource</td>
<td>$row->payment_agencyulo</td>
<td>$row->payment_agencyproject</td>
<td>$$row->payment_disbustment</td>
<td>$row->payment_payeename</td>
<td>$row->payment_processpayment</td>
</tr>
Expenditure;
It will error if there is a space on PHP 7.0.33.
I just wanted to add this case as well for VARCHAR
foreign key relation. I spent the last week trying to figure this out in MySQL Workbench 8.0 and was finally able to fix the error.
Short Answer: The character set and collation of the schema, the table, the column, the referencing table, the referencing column and any other tables that reference to the parent table have to match.
Long Answer:
I had an ENUM datatype in my table. I changed this to VARCHAR
and I can get the values from a reference table so that I don't have to alter the parent table to add additional options. This foreign-key relationship seemed straightforward but I got 1215 error. arvind's answer and the following link suggested the use of
SHOW ENGINE INNODB STATUS;
On using this command I got the following verbose description for the error with no additional helpful information
Cannot find an index in the referenced table where the referenced columns appear as the first columns, or column types in the table and the referenced table do not match for constraint. Note that the internal storage type of ENUM and SET changed in tables created with >= InnoDB-4.1.12, and such columns in old tables cannot be referenced by such columns in new tables. Please refer to http://dev.mysql.com/doc/refman/8.0/en/innodb-foreign-key-constraints.html for correct foreign key definition.
After which I used SET FOREIGN_KEY_CHECKS=0;
as suggested by Arvind Bharadwaj and the link here:
This gave the following error message:
Error Code: 1822. Failed to add the foreign key constraint. Missing index for constraint
At this point, I 'reverse engineer'-ed the schema and I was able to make the foreign-key relationship in the EER diagram. On 'forward engineer'-ing, I got the following error:
Error 1452: Cannot add or update a child row: a foreign key constraint fails
When I 'forward engineer'-ed the EER diagram to a new schema, the SQL script ran without issues. On comparing the generated SQL from the attempts to forward engineer, I found that the difference was the character set and collation. The parent table, child table and the two columns had utf8mb4
character set and utf8mb4_0900_ai_ci
collation, however, another column in the parent table was referenced using CHARACTER SET = utf8 , COLLATE = utf8_bin ;
to a different child table.
For the entire schema, I changed the character set and collation for all the tables and all the columns to the following:
CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci;
This finally solved my problem with 1215 error.
Side Note:
The collation utf8mb4_general_ci
works in MySQL Workbench 5.0 or later. Collation utf8mb4_0900_ai_ci
works just for MySQL Workbench 8.0 or higher. I believe one of the reasons I had issues with character set and collation is due to MySQL Workbench upgrade to 8.0 in between. Here is a link that talks more about this collation.
If your goal is only to take the files and not the folder, the approach I made was to use the file size
as a filter. This property is the current size of the file hosted by AWS. All the folders return 0 in that property.
The following is a C# code using linq but it shouldn't be hard to translate to Java.
var amazonClient = new AmazonS3Client(key, secretKey, region);
var listObjectsRequest= new ListObjectsRequest
{
BucketName = 'someBucketName',
Delimiter = 'someDelimiter',
Prefix = 'somePrefix'
};
var objects = amazonClient.ListObjects(listObjectsRequest);
var objectsInFolder = objects.S3Objects.Where(file => file.Size > 0).ToList();
You do not need to limit your compiler to only armv7 and armv7s by removing arm64 setting from supported architectures. You just need to set Deployment target setting to 5.1.1
Important note: you cannot set Deployment target to 5.1.1 in Build Settings section because it is drop-down only with fixed values. But you can easily set it to 5.1.1 in General section of application settings by just typing the value in text field.
You can use this dummy plugin:
mvn archetype:generate -DgroupId=org.eclipse.m2e -DartifactId=lifecycle-mapping -Dversion=1.0.0 -DarchetypeArtifactId=maven-archetype-mojo
After generating the project install/deploy it.
This is version from "Henry Vilinskiy" adapted for MySQL and Kilometers:
CREATE FUNCTION `CalculateDistanceInKm`(
fromLatitude float,
fromLongitude float,
toLatitude float,
toLongitude float
) RETURNS float
BEGIN
declare distance float;
select
6367 * ACOS(
round(
COS(RADIANS(90-fromLatitude)) *
COS(RADIANS(90-toLatitude)) +
SIN(RADIANS(90-fromLatitude)) *
SIN(RADIANS(90-toLatitude)) *
COS(RADIANS(fromLongitude-toLongitude))
,15)
)
into distance;
return round(distance,3);
END;
You can use some div or span instead of button and then on click call some function which submits form at he end.
<form id="my_form">
<span onclick="submit()">submit</span>
</form>
<script>
function submit()
{
//do something
$("#my_form").submit();
}
</script>
Apparently \r
is the key!
$ sed 's/, /\r/g' file3.txt > file4.txt
Transformed this:
ABFS, AIRM, AMED, BOSC, CALI, ECPG, FRGI, GERN, GTIV, HSON, IQNT, JRCC, LTRE,
MACK, MIDD, NKTR, NPSP, PME, PTIX, REFR, RSOL, UBNT, UPI, YONG, ZEUS
To this:
ABFS
AIRM
AMED
BOSC
CALI
ECPG
FRGI
GERN
GTIV
HSON
IQNT
JRCC
LTRE
MACK
MIDD
NKTR
NPSP
PME
PTIX
REFR
RSOL
UBNT
UPI
YONG
ZEUS
Once I'd discovered all the information of how my client was handling the encryption/decryption at their end it was straight forward using the AesManaged example suggested by dtb.
The finally implemented code started like this:
try
{
// Create a new instance of the AesManaged class. This generates a new key and initialization vector (IV).
AesManaged myAes = new AesManaged();
// Override the cipher mode, key and IV
myAes.Mode = CipherMode.ECB;
myAes.IV = new byte[16] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // CRB mode uses an empty IV
myAes.Key = CipherKey; // Byte array representing the key
myAes.Padding = PaddingMode.None;
// Create a encryption object to perform the stream transform.
ICryptoTransform encryptor = myAes.CreateEncryptor();
// TODO: perform the encryption / decryption as required...
}
catch (Exception ex)
{
// TODO: Log the error
throw ex;
}
As others recommend, you can use Oracle SQL Developer. You can point to the location of the script to run it, as described. A slightly simpler method, though, is to just use drag-and-drop:
Other answers already explained the difference between user and kernel mode. If you really want to get into detail you should get a copy of Windows Internals, an excellent book written by Mark Russinovich and David Solomon describing the architecture and inside details of the various Windows operating systems.
I'd suggest marking the Hibernate DAO class with @Primary
, i.e. (assuming you used @Repository
on HibernateDeviceDao
):
@Primary
@Repository
public class HibernateDeviceDao implements DeviceDao
This way it will be selected as the default autowire candididate, with no need to autowire-candidate
on the other bean.
Also, rather than using @Autowired @Qualifier
, I find it more elegant to use @Resource
for picking specific beans, i.e.
@Resource(name="jdbcDeviceDao")
DeviceDao deviceDao;
Here is a one liner that is used to get yesterdays date in format YYYY-MM-DD in text and handle the timezone offset.
new Date(Date.now() - 1 * 86400000 - new Date().getTimezoneOffset() * 60000).toISOString().split('T')[0]
It can obviusly changed to return date, x days back in time. To include time etc.
console.log(Date())_x000D_
console.log(new Date(Date.now() - 1 * 86400000 - new Date().getTimezoneOffset() * 60000).toISOString().split('T')[0]); // "2019-11-11"_x000D_
console.log(new Date(Date.now() - 1 * 86400000 - new Date().getTimezoneOffset() * 60000).toISOString().split('.')[0].replace('T',' ')); // "2019-11-11 11:11:11"_x000D_
_x000D_
// that is: [dates] * 24 * 60 * 60 * 1000 - offsetinmin * 60 * 1000 // this is: [dates] * 24 * 60 * 60 * 1000 - offsetinmin * 60 * 1000
_x000D_
XPath 1.0 doesn't handle regex natively, you could try something like
//*[starts-with(@id, 'sometext') and ends-with(@id, '_text')]
(as pointed out by paul t, //*[boolean(number(substring-before(substring-after(@id, "sometext"), "_text")))]
could be used to perform the same check your original regex does, if you need to check for middle digits as well)
In XPath 2.0, try
//*[matches(@id, 'sometext\d+_text')]
It is possible to play a local video file.
<input type="file" accept="video/*"/>
<video controls autoplay></video>
When a file is selected via the input
element:
input.files
FileListvideo.src
propertyLean back and watch :)
http://jsfiddle.net/dsbonev/cCCZ2/embedded/result,js,html,css/
(function localFileVideoPlayer() {_x000D_
'use strict'_x000D_
var URL = window.URL || window.webkitURL_x000D_
var displayMessage = function(message, isError) {_x000D_
var element = document.querySelector('#message')_x000D_
element.innerHTML = message_x000D_
element.className = isError ? 'error' : 'info'_x000D_
}_x000D_
var playSelectedFile = function(event) {_x000D_
var file = this.files[0]_x000D_
var type = file.type_x000D_
var videoNode = document.querySelector('video')_x000D_
var canPlay = videoNode.canPlayType(type)_x000D_
if (canPlay === '') canPlay = 'no'_x000D_
var message = 'Can play type "' + type + '": ' + canPlay_x000D_
var isError = canPlay === 'no'_x000D_
displayMessage(message, isError)_x000D_
_x000D_
if (isError) {_x000D_
return_x000D_
}_x000D_
_x000D_
var fileURL = URL.createObjectURL(file)_x000D_
videoNode.src = fileURL_x000D_
}_x000D_
var inputNode = document.querySelector('input')_x000D_
inputNode.addEventListener('change', playSelectedFile, false)_x000D_
})()
_x000D_
video,_x000D_
input {_x000D_
display: block;_x000D_
}_x000D_
_x000D_
input {_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
.info {_x000D_
background-color: aqua;_x000D_
}_x000D_
_x000D_
.error {_x000D_
background-color: red;_x000D_
color: white;_x000D_
}
_x000D_
<h1>HTML5 local video file player example</h1>_x000D_
<div id="message"></div>_x000D_
<input type="file" accept="video/*" />_x000D_
<video controls autoplay></video>
_x000D_
Use the ng-form directive inside of the tag in which you are using the ng-repeat directive. You can then use the scope created by the ng-form directive to reference a generic name. For example:
<div class="form-group col-sm-6" data-ng-form="subForm" data-ng-repeat="field in justificationInfo.justifications"">
<label for="{{field.label}}"><h3>{{field.label}}</h3></label>
<i class="icon-valid" data-ng-show="subForm.input.$dirty && subForm.input.$valid"></i>
<i class="icon-invalid" data-ng-show="subForm.input.$dirty && subForm.input.$invalid"></i>
<textarea placeholder="{{field.placeholder}}" class="form-control" id="{{field.label}}" name="input" type="text" rows="3" data-ng-model="field.value" required>{{field.value}}</textarea>
</div>
Credit to: http://www.benlesh.com/2013/03/angular-js-validating-form-elements-in.html
I'm not sure whether you think about:
select * from friend f
where not exists (
select 1 from likes l where f.id1 = l.id and f.id2 = l.id2
)
it works only if id1 is related with id1 and id2 with id2 not both.
Before truncating the tables you have to remove all foreign keys. Use this script to generate final scripts to drop and recreate all foreign keys in database. Please set the @action variable to 'CREATE' or 'DROP'.
if you wanna keep OOP form without turning any error off, you can also:
class A
{
public function foo() {
;
}
}
class B extends A
{
/*instead of :
public function foo($a, $b, $c) {*/
public function foo() {
list($a, $b, $c) = func_get_args();
// ...
}
}
Sounds like you just need a UINavigationController
setup?
You can get the AppDelegate
anywhere in the program via
YourAppDelegateName* blah = (YourAppDelegateName*)[[UIApplication sharedApplication]delegate];
In your app delegate you should have your navigation controller setup, either via IB or in code.
In code, assuming you've created your 'House overview' viewcontroller already it would be something like this in your AppDelegate
didFinishLaunchingWithOptions
...
self.m_window = [[[UIWindow alloc]initWithFrame:[[UIScreen mainScreen]bounds] autorelease];
self.m_navigationController = [[[UINavigationController alloc]initWithRootViewController:homeViewController]autorelease];
[m_window addSubview:self.m_navigationController.view];
After this you just need a viewcontroller per 'room' and invoke the following when a button click event is picked up...
YourAppDelegateName* blah = (YourAppDelegateName*)[[UIApplication sharedApplication]delegate];
[blah.m_navigationController pushViewController:newRoomViewController animated:YES];
I've not tested the above code so forgive any syntax errors but hope the pseudo code is of help...
It shouldn't be HTTP headers if the file has been downloaded successfully and it's the same file that you can open from OI.
A shot in the dark, but could it be that you are not allowing installation from unknown sources, and that OI is somehow bypassing that?
Settings > Applications > Unknown sources...
Edit
Answer extracted from comments which worked. Ensure the Content-Type is set to application/vnd.android.package-archive
This might help you
public static string TransformDocument(string doc, string stylesheetPath)
{
Func<string,XmlDocument> GetXmlDocument = (xmlContent) =>
{
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xmlContent);
return xmlDocument;
};
try
{
var document = GetXmlDocument(doc);
var style = GetXmlDocument(File.ReadAllText(stylesheetPath));
System.Xml.Xsl.XslCompiledTransform transform = new System.Xml.Xsl.XslCompiledTransform();
transform.Load(style); // compiled stylesheet
System.IO.StringWriter writer = new System.IO.StringWriter();
XmlReader xmlReadB = new XmlTextReader(new StringReader(document.DocumentElement.OuterXml));
transform.Transform(xmlReadB, null, writer);
return writer.ToString();
}
catch (Exception ex)
{
throw ex;
}
}
Just another way not mentioned yet:
If you installed it locally to a project then open up the node_modules folder and check your webpack module.
$cd /node_modules/webpack/package.json
Open the package.json file and look under version
Use ssh for that purpose. Generate keys without using a password and place it to .authorized_keys at the remote machine. Create the script to be run remotely, copy it to the other machine and then just run it remotely using ssh.
I used this approach many times with a big success. Also note that it is much more secure than telnet.
There are various Inline
elements that can help you, for the simplest formatting options you can use Bold
, Italic
and Underline
:
<TextBlock>
Sample text with <Bold>bold</Bold>, <Italic>italic</Italic> and <Underline>underlined</Underline> words.
</TextBlock>
I think it is worth noting, that those elements are in fact just shorthands for Span
elements with various properties set (i.e.: for Bold
, the FontWeight
property is set to FontWeights.Bold
).
This brings us to our next option: the aforementioned Span
element.
You can achieve the same effects with this element as above, but you are granted even more possibilities; you can set (among others) the Foreground
or the Background
properties:
<TextBlock>
Sample text with <Span FontWeight="Bold">bold</Span>, <Span FontStyle="Italic">italic</Span> and <Span TextDecorations="Underline">underlined</Span> words. <Span Foreground="Blue">Coloring</Span> <Span Foreground="Red">is</Span> <Span Background="Cyan">also</Span> <Span Foreground="Silver">possible</Span>.
</TextBlock>
The Span
element may also contain other elements like this:
<TextBlock>
<Span FontStyle="Italic">Italic <Span Background="Yellow">text</Span> with some <Span Foreground="Blue">coloring</Span>.</Span>
</TextBlock>
There is another element, which is quite similar to Span
, it is called Run
. The Run
cannot contain other inline elements while the Span
can, but you can easily bind a variable to the Run
's Text
property:
<TextBlock>
Username: <Run FontWeight="Bold" Text="{Binding UserName}"/>
</TextBlock>
Also, you can do the whole formatting from code-behind if you prefer:
TextBlock tb = new TextBlock();
tb.Inlines.Add("Sample text with ");
tb.Inlines.Add(new Run("bold") { FontWeight = FontWeights.Bold });
tb.Inlines.Add(", ");
tb.Inlines.Add(new Run("italic ") { FontStyle = FontStyles.Italic });
tb.Inlines.Add("and ");
tb.Inlines.Add(new Run("underlined") { TextDecorations = TextDecorations.Underline });
tb.Inlines.Add("words.");
You can try
Random r = new Random();
int rInt = r.Next(0, 100); //for ints
int range = 100;
double rDouble = r.NextDouble()* range; //for doubles
Have a look at
Random Class, Random.Next Method (Int32, Int32) and Random.NextDouble Method
Extending off of Rapti's answer, this should work just as well, but it adds more margin to the right side of the body
and hides it with negative html
margin, instead of adding extra padding that could potentially affect the page's layout. This way, nothing is changed on the actual page (in most cases), and the code is still functional.
html {
margin-right: calc(100% - 100vw);
}
body {
margin-right: calc(100vw - 100%);
}
If you are planning to use appending more then once, you might want to write a function:
//Append text to input element
function jQ_append(id_of_input, text){
var input_id = '#'+id_of_input;
$(input_id).val($(input_id).val() + text);
}
After you can just call it:
jQ_append('my_input_id', 'add this text');
You even can use require of your JSON without specifying the extension .json. It will let you change the file extension to .js without any changes in your imports.
assuming we have ./myJsonFile.json in the same directory.
const data = require('./myJsonFile')
If in the future you'll change ./myJsonFile.json to ./myJsonFile.js nothing should be changed in the import.
First of all I'd like to say that I 100% agree with John Saunders that you must avoid loops in SQL in most cases especially in production.
But occasionally as a one time thing to populate a table with a hundred records for testing purposes IMHO it's just OK to indulge yourself to use a loop.
For example in your case to populate your table with records with hospital ids between 16 and 100 and make emails and descriptions distinct you could've used
CREATE PROCEDURE populateHospitals
AS
DECLARE @hid INT;
SET @hid=16;
WHILE @hid < 100
BEGIN
INSERT hospitals ([Hospital ID], Email, Description)
VALUES(@hid, 'user' + LTRIM(STR(@hid)) + '@mail.com', 'Sample Description' + LTRIM(STR(@hid)));
SET @hid = @hid + 1;
END
And result would be
ID Hospital ID Email Description
---- ----------- ---------------- ---------------------
1 16 [email protected] Sample Description16
2 17 [email protected] Sample Description17
...
84 99 [email protected] Sample Description99
<br>
and <br />
render differently in some browsers, so choosing either over the other isn't going to hurt your project, but do expect a bulk find..replace to affect the page render in some browsers, which may result in extra work for yourself or even embarrassment should the change affect nothing in your test browser, but break it in the preferred browser of your clients'.
I prefer <br>
since it is what I have used since Erwise and Netscape Navigator (early web browsers), but there's no reason not to choose <br />
instead. It may be useful for some preprocessing, comparability, etc.
Even if your choice boils down to preferring the look of one over the other, or you (or your favourite HTML editor e.g. Dreamweaver) might like your code to be xml compliant. It's up to you.
A quick side note:
Not to be confused with br
, but in addition you may also consider using wbr
tags in your HTML: A word break opportunity tag, which specifies where in a text it would be ok to add a line-break.
For further reading, please have a read of the HTML5 spec.
Further to ericwa's answer. CHECK constraints can enable a pseudo boolean column by enforcing a TEXT datatype and only allowing TRUE or FALSE case specific values e.g.
CREATE TABLE IF NOT EXISTS "boolean_test"
(
"id" INTEGER PRIMARY KEY AUTOINCREMENT
, "boolean" TEXT NOT NULL
CHECK( typeof("boolean") = "text" AND
"boolean" IN ("TRUE","FALSE")
)
);
INSERT INTO "boolean_test" ("boolean") VALUES ("TRUE");
INSERT INTO "boolean_test" ("boolean") VALUES ("FALSE");
INSERT INTO "boolean_test" ("boolean") VALUES ("TEST");
Error: CHECK constraint failed: boolean_test
INSERT INTO "boolean_test" ("boolean") VALUES ("true");
Error: CHECK constraint failed: boolean_test
INSERT INTO "boolean_test" ("boolean") VALUES ("false");
Error: CHECK constraint failed: boolean_test
INSERT INTO "boolean_test" ("boolean") VALUES (1);
Error: CHECK constraint failed: boolean_test
select * from boolean_test;
id boolean
1 TRUE
2 FALSE
Like this
class CustomDictOne(dict):
def __init__(self,*arg,**kw):
super(CustomDictOne, self).__init__(*arg, **kw)
Now you can use the built-in functions, like dict.get()
as self.get()
.
You do not need to wrap a hidden self._dict
. Your class already is a dict.
Here is a guide by @CTS_AE on how to use NPM with standalone node.exe: https://stackoverflow.com/a/31148216/228508
Just setting the return value to the function name is still not exactly the same as the Java (or other) return
statement, because in java, return
exits the function, like this:
public int test(int x) {
if (x == 1) {
return 1; // exits immediately
}
// still here? return 0 as default.
return 0;
}
In VB, the exact equivalent takes two lines if you are not setting the return value at the end of your function. So, in VB the exact corollary would look like this:
Public Function test(ByVal x As Integer) As Integer
If x = 1 Then
test = 1 ' does not exit immediately. You must manually terminate...
Exit Function ' to exit
End If
' Still here? return 0 as default.
test = 0
' no need for an Exit Function because we're about to exit anyway.
End Function
Since this is the case, it's also nice to know that you can use the return variable like any other variable in the method. Like this:
Public Function test(ByVal x As Integer) As Integer
test = x ' <-- set the return value
If test <> 1 Then ' Test the currently set return value
test = 0 ' Reset the return value to a *new* value
End If
End Function
Or, the extreme example of how the return variable works (but not necessarily a good example of how you should actually code)—the one that will keep you up at night:
Public Function test(ByVal x As Integer) As Integer
test = x ' <-- set the return value
If test > 0 Then
' RECURSIVE CALL...WITH THE RETURN VALUE AS AN ARGUMENT,
' AND THE RESULT RESETTING THE RETURN VALUE.
test = test(test - 1)
End If
End Function
Run the installer from command line with argument /CustomInstallPath
InstallationDirectory
See more command-line parameters and other installation information.
Note: this won't change location of all files, but only of those which can be (by design) installed onto different location. Be warned that there is many shared components which will be installed into shared repositories on drive C:
without any possibility to change their path (unless you do some hacking using mklink /j
(directory junction, i.e."hard link for folder"), but it is questionable whether it is worth it, because any Visual Studio updates will break those hard links. This is confirmed by people who tried that, although on Visual Studio 2012.)
Update: per recent comment, uninstallation of Visual Studio might be required before the above applies. Uninstallation command is like this: vs_community_ENU.exe /uninstall /force
If you want a newline, you have to write one explicitly. The usual way is like this:
hs.write(name + "\n")
This uses a backslash escape, \n
, which Python converts to a newline character in string literals. It just concatenates your string, name
, and that newline character into a bigger string, which gets written to the file.
It's also possible to use a multi-line string literal instead, which looks like this:
"""
"""
Or, you may want to use string formatting instead of concatenation:
hs.write("{}\n".format(name))
All of this is explained in the Input and Output chapter in the tutorial.
Try it like this
String s="test string(67)";
String requiredString = s.substring(s.indexOf("(") + 1, s.indexOf(")"));
The method's signature for substring is:
s.substring(int start, int end);
You can't "add" values to an array as the array length is immutable. You can set values at specific array positions.
If you know how to do it with one-dimensional arrays then you know how to do it with n-dimensional arrays: There are no n-dimensional arrays in Java, only arrays of arrays (of arrays...).
But you can chain the index operator for array element access.
String[][] x = new String[2][];
x[0] = new String[1];
x[1] = new String[2];
x[0][0] = "a1";
// No x[0][1] available
x[1][0] = "b1";
x[1][1] = "b2";
Note the dimensions of the child arrays don't need to match.
You can do
var arr = _.values(obj);
For documentation see here.
See ?merge
:
the name "row.names" or the number 0 specifies the row names.
Example:
R> de <- merge(d, e, by=0, all=TRUE) # merge by row names (by=0 or by="row.names")
R> de[is.na(de)] <- 0 # replace NA values
R> de
Row.names a b c d e f g h i j k l m n o p q r s
1 1 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10 11 12 13 14 15 16 17 18 19
2 2 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 0 0 0 0 0 0 0 0 0
3 3 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0 21 22 23 24 25 26 27 28 29
t
1 20
2 0
3 30
Use sql
from sql
:
spool output of this to a file:
select 'alter index '||owner||'.'||index_name||' rebuild tablespace TO_TABLESPACE_NAME;' from all_indexes where owner='OWNERNAME';
spoolfile will have something like this:
alter index OWNER.PK_INDEX rebuild tablespace CORRECT_TS_NAME;
Mono is a runtime environment that can run .NET applications and that works on both Windows and Linux. It includes a C# compiler.
As an IDE, you could use MonoDevelop, and I suppose there's something available for Eclipse, too.
Note that WinForms support on Mono is there, but somewhat lacking. Generally, Mono developers seem to prefer different GUI toolkits such as Gtk#.
I would suggest you are looking at the problem in the wrong light. The questtion should be 'what am i doing that needs 2G memory inside a apache process with Php via apache module and is this tool set best suited for the job?'
Yes you can strap a rocket onto a ford pinto, but it's probably not the right solution.
Regardless, I'll provide the rocket if you really need it... you can add to the top of the script.
ini_set('memory_limit','2048M');
This will set it for just the script. You will still need to tell apache to allow that much for a php script (I think).
Here is what i tried to do to add parameter in the url which contain the specific character in the url.
jQuery('a[href*="google.com"]').attr('href', function(i,href) {
//jquery date addition
var requiredDate = new Date();
var numberOfDaysToAdd = 60;
requiredDate.setDate(requiredDate.getDate() + numberOfDaysToAdd);
//var convertedDate = requiredDate.format('d-M-Y');
//var newDate = datepicker.formatDate('yy/mm/dd', requiredDate );
//console.log(requiredDate);
var month = requiredDate.getMonth()+1;
var day = requiredDate.getDate();
var output = requiredDate.getFullYear() + '/' + ((''+month).length<2 ? '0' : '') + month + '/' + ((''+day).length<2 ? '0' : '') + day;
//
Working Example Click
Simple and easy:
$this->db->order_by("name", "asc");
$query = $this->db->get($this->table_name);
return $query->result();
You can use closures to pass parameters:
iframe.document.addEventListener('click', function(event) {clic(this.id);}, false);
However, I recommend that you use a better approach to access your frame (I can only assume that you are using the DOM0 way of accessing frame windows by their name - something that is only kept around for backwards compatibility):
document.getElementById("myFrame").contentDocument.addEventListener(...);
My approach:
define a default constraint on the ModDate
column with a value of GETDATE()
- this handles the INSERT
case
have a AFTER UPDATE
trigger to update the ModDate
column
Something like:
CREATE TRIGGER trg_UpdateTimeEntry
ON dbo.TimeEntry
AFTER UPDATE
AS
UPDATE dbo.TimeEntry
SET ModDate = GETDATE()
WHERE ID IN (SELECT DISTINCT ID FROM Inserted)
Workstation doesn't have a wireless NIC type, so direct wireless hardware access is out. If you just want to access through the extant host wireless connection, bridging is your answer.
I think the only way to get a wireless NIC dedicated to the VM would be using a USB wireless NIC as a USB-passthrough device on the VM. When you have Workstation running and a USB device plugged in, it should give you an option to change whether that device is connected to the host or to the VM.
Remove the display:none
, and use ng-show
instead:
<ul class="procedures">
<li ng-repeat="procedure in procedures | filter:query | orderBy:orderProp">
<h4><a href="#" ng-click="showDetails = ! showDetails">{{procedure.definition}}</a></h4>
<div class="procedure-details" ng-show="showDetails">
<p>Number of patient discharges: {{procedure.discharges}}</p>
<p>Average amount covered by Medicare: {{procedure.covered}}</p>
<p>Average total payments: {{procedure.payments}}</p>
</div>
</li>
</ul>
Here's the fiddle: http://jsfiddle.net/asmKj/
You can also use ng-class
to toggle a class:
<div class="procedure-details" ng-class="{ 'hidden': ! showDetails }">
I like this more, since it allows you to do some nice transitions: http://jsfiddle.net/asmKj/1/
The alternative for explode in php is split.
The first parameter is the delimiter, the second parameter the maximum number splits. The parts are returned without the delimiter present (except possibly the last part). When the delimiter is None, all whitespace is matched. This is the default.
>>> "Rajasekar SP".split()
['Rajasekar', 'SP']
>>> "Rajasekar SP".split('a',2)
['R','j','sekar SP']
You can try this:
''' lst: list of dictionaries '''
lst = [{"name": "Tom", "age": 10}, {"name": "Mark", "age": 5}, {"name": "Pam", "age": 7}]
search = raw_input("What name: ") #Input name that needs to be searched (say 'Pam')
print [ lst[i] for i in range(len(lst)) if(lst[i]["name"]==search) ][0] #Output
>>> {'age': 7, 'name': 'Pam'}
Use like this
<a href="index.php">Index Page</a>
<a href="page2.php">Page 2</a>
One more thing you have to keep in mind that the APPEND() method in Pandas doesn't modify the original object. Instead it creates a new one with combined data. Because of involving creation and data buffer, its performance is not well. You'd better use CONCAT() function when doing multi-APPEND operations.
omg I'm lacking 7 rep to make comments. This is @Raptor's & @Tomm's comment, since this question still shows up way high in google serps.
He's exactly right. For small files file($file);
is perfectly fine. For large files it's total overkill b/c php arrays eat memory like crazy.
I just ran a tiny test with a *.csv with a file size of ~67mb (1,000,000 lines):
$t = -microtime(1);
$file = '../data/1000k.csv';
$lines = file($file);
echo $lines[999999]
."\n".(memory_get_peak_usage(1)/1024/1024)
."\n".($t+microtime(1));
//227.5
//0.22701287269592
//Process finished with exit code 0
And since noone mentioned it yet, I gave the SplFileObject
a try, which I actually just recently discovered for myself.
$t = -microtime(1);
$file = '../data/1000k.csv';
$spl = new SplFileObject($file);
$spl->seek(999999);
echo $spl->current()
."\n".(memory_get_peak_usage(1)/1024/1024)
."\n".($t+microtime(1));
//0.5
//0.11500692367554
//Process finished with exit code 0
This was on my Win7 desktop so it's not representative for production environment, but still ... quite the difference.
if it's background, use background-size: cover;
body{_x000D_
background-image: url('http://i.stack.imgur.com/kx8MT.gif');_x000D_
background-size: cover;_x000D_
_x000D_
_x000D_
_x000D_
height: 100vh;_x000D_
padding:0;_x000D_
margin:0;_x000D_
}
_x000D_
This particular error implies that one of the variables being used in the arithmetic on the line has a shape incompatible with another on the same line (i.e., both different and non-scalar). Since n
and the output of np.add.reduce()
are both scalars, this implies that the problem lies with xm
and ym
, the two of which are simply your x
and y
inputs minus their respective means.
Based on this, my guess is that your x
and y
inputs have different shapes from one another, making them incompatible for element-wise multiplication.
** Technically, it's not that variables on the same line have incompatible shapes. The only problem is when two variables being added, multiplied, etc., have incompatible shapes, whether the variables are temporary (e.g., function output) or not. Two variables with different shapes on the same line are fine as long as something else corrects the issue before the mathematical expression is evaluated.
For those still struggling with the error, make sure that you also import ReactiveFormsModule in your component 's module.ts file
meaning that you will import your ReactiveFormsModule in your app.module.ts and also in your mycomponent.module.ts file
get current activity from parent, then using this code
getActivity().getSupportFragmentManager()
1) Best practice is to make new javascript file like my.js. Make this file into your js folder in root directory -> js/my.js . 2) In my.js file add your code inside of $(document).ready(function(){}) scope.
$(document).ready(function(){
$(".icon-bg").click(function () {
$(".btn").toggleClass("active");
$(".icon-bg").toggleClass("active");
$(".container").toggleClass("active");
$(".box-upload").toggleClass("active");
$(".box-caption").toggleClass("active");
$(".box-tags").toggleClass("active");
$(".private").toggleClass("active");
$(".set-time-limit").toggleClass("active");
$(".button").toggleClass("active");
});
$(".button").click(function () {
$(".button-overlay").toggleClass("active");
});
$(".iconmelon").click(function () {
$(".box-upload-ing").toggleClass("active");
$(".iconmelon-loaded").toggleClass("active");
});
$(".private").click(function () {
$(".private-overlay").addClass("active");
$(".private-overlay-wave").addClass("active");
});
});
3) add your new js file into your html
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="/js/my.js"></script>
</head>
I think you could have used:
value.ToString("F"+NumberOfDecimals)
value = 10,502
value.ToString("F2") //10,50
value = 10,5
value.ToString("F2") //10,50
Here is a detailed description of Numeric Format Strings
Start the project structure( file>structure
)
You can see:
on the left, modules list;
on the right, Properties>Build
Tools Version
there maybe are more than one modules.
change "Build Tools Version"
for every Module.
it works.
It can be caused by a classpath contamination. Check that you /WEB-INF/lib
doesn't contain something like jsp-api-*.jar
.
Its important to mention that once in 4-5 years this method might give a 1 second error, becase of a leap-second (http://www.nist.gov/pml/div688/leapseconds.cfm), and the correct formula for that day would be
(24*60*60 + 1) * 1000
There is a question Are leap seconds catered for by Calendar? and the answer is no.
So, if You're designing super time-dependant software, be careful about this formula.
The issue isn't with the button, the issue is with the div
. As div
s are block elements, they default to occupying the full width of their parent element (as a general rule; I'm pretty sure there are some exceptions if you're messing around with different positioning schemes in one document that would cause it to occupy the full width of a higher element in the hierarchy).
Anyway, try adding float: left;
to the rules for the .button
selector. That will cause the div
with class button
to fit around the button, and would allow you to have multiple floated div
s on the same line if you wanted more div.button
s.
I don't think having a list of chars to remove is safe. I would rather use the following:
For filenames: Use an internal ID or a hash of the filecontent. Save the document name in a database. This way you can keep the original filename and still find the file.
For url parameters: Use urlencode()
to encode any special characters.
Maybe it is just my Java and C background showing, but I prefer CamelCase (CapCase) over punctuation in the name. My workgroup uses such names, probably to match the names of the app or service the repository contains.
In Mastering Web Application Development with AngularJS book p.19, it is written that
Avoid direct bindings to scope's properties. Two-way data binding to object's properties (exposed on a scope) is a preferred approach. As a rule of thumb, you should have a dot in an expression provided to the ng-model directive (for example, ng-model="thing.name").
Scopes are just JavaScript objects, and they mimic dom hierarchy. According to JavaScript Prototype Inheritance, scopes properties are separated through scopes. To avoid this, dot notation should use to bind ng-models.
you can do a multi div layout like this
<div class="fieldcontainer">
<div class="label"></div>
<div class="field"></div>
</div>
where .fieldcontainer { clear: both; } .label { float: left; width: ___ } .field { float: left; }
Or, I actually prefer tables for forms like this. This is very much tabular data and it comes out very clean. Both will work though.
Think about somebody doing help(yourmodule)
at the interactive interpreter's prompt — what do they want to know? (Other methods of extracting and displaying the information are roughly equivalent to help
in terms of amount of information). So if you have in x.py
:
"""This module does blah blah."""
class Blah(object):
"""This class does blah blah."""
then:
>>> import x; help(x)
shows:
Help on module x:
NAME
x - This module does blah blah.
FILE
/tmp/x.py
CLASSES
__builtin__.object
Blah
class Blah(__builtin__.object)
| This class does blah blah.
|
| Data and other attributes defined here:
|
| __dict__ = <dictproxy object>
| dictionary for instance variables (if defined)
|
| __weakref__ = <attribute '__weakref__' of 'Blah' objects>
| list of weak references to the object (if defined)
As you see, the detailed information on the classes (and functions too, though I'm not showing one here) is already included from those components' docstrings; the module's own docstring should describe them very summarily (if at all) and rather concentrate on a concise summary of what the module as a whole can do for you, ideally with some doctested examples (just like functions and classes ideally should have doctested examples in their docstrings).
I don't see how metadata such as author name and copyright / license helps the module's user — it can rather go in comments, since it could help somebody considering whether or not to reuse or modify the module.
We can take a mysql dump of any particular table with any given condition like below
mysqldump -uusername -p -hhost databasename tablename --skip-lock-tables
If we want to add a specific where condition on table then we can use the following command
mysqldump -uusername -p -hhost databasename tablename --where="date=20140501" --skip-lock-tables
I am using create-react-app which comes with jest by default and enzyme 2.7.0.
This worked for me:
const wrapper = mount(<EditableText defaultValue="Hello" />);
const input = wrapper.find('input')[index]; // where index is the position of the input field of interest
input.node.value = 'Change';
input.simulate('change', input);
done();
If I'm not mistaken, the default bean name of a bean declared with @Component is the name of its class its first letter in lower-case. This means that
@Component
public class SuggestionService {
declares a bean of type SuggestionService
, and of name suggestionService
. It's equivalent to
@Component("suggestionService")
public class SuggestionService {
or to
<bean id="suggestionService" .../>
You're redefining another bean of the same type, but with a different name, in the XML:
<bean id="SuggestionService" class="com.hp.it.km.search.web.suggestion.SuggestionService">
...
</bean>
So, either specify the name of the bean in the annotation to be SuggestionService
, or use the ID suggestionService
in the XML (don't forget to also modify the <ref>
element, or to remove it, since it isn't needed). In this case, the XML definition will override the annotation definition.
You go around making your webpage, and keep on putting {{data bindings}} whenever you feel you would have dynamic data. Angular will then provide you a $scope handler, which you can populate (statically or through calls to the web server).
This is a good understanding of data-binding. I think you've got that down.
For simple DOM manipulation, which doesnot involve data manipulation (eg: color changes on mousehover, hiding/showing elements on click), jQuery or old-school js is sufficient and cleaner. This assumes that the model in angular's mvc is anything that reflects data on the page, and hence, css properties like color, display/hide, etc changes dont affect the model.
I can see your point here about "simple" DOM manipulation being cleaner, but only rarely and it would have to be really "simple". I think DOM manipulation is one the areas, just like data-binding, where Angular really shines. Understanding this will also help you see how Angular considers its views.
I'll start by comparing the Angular way with a vanilla js approach to DOM manipulation. Traditionally, we think of HTML as not "doing" anything and write it as such. So, inline js, like "onclick", etc are bad practice because they put the "doing" in the context of HTML, which doesn't "do". Angular flips that concept on its head. As you're writing your view, you think of HTML as being able to "do" lots of things. This capability is abstracted away in angular directives, but if they already exist or you have written them, you don't have to consider "how" it is done, you just use the power made available to you in this "augmented" HTML that angular allows you to use. This also means that ALL of your view logic is truly contained in the view, not in your javascript files. Again, the reasoning is that the directives written in your javascript files could be considered to be increasing the capability of HTML, so you let the DOM worry about manipulating itself (so to speak). I'll demonstrate with a simple example.
<div rotate-on-click="45"></div>
First, I'd just like to comment that if we've given our HTML this functionality via a custom Angular Directive, we're already done. That's a breath of fresh air. More on that in a moment.
function rotate(deg, elem) {
$(elem).css({
webkitTransform: 'rotate('+deg+'deg)',
mozTransform: 'rotate('+deg+'deg)',
msTransform: 'rotate('+deg+'deg)',
oTransform: 'rotate('+deg+'deg)',
transform: 'rotate('+deg+'deg)'
});
}
function addRotateOnClick($elems) {
$elems.each(function(i, elem) {
var deg = 0;
$(elem).click(function() {
deg+= parseInt($(this).attr('rotate-on-click'), 10);
rotate(deg, this);
});
});
}
addRotateOnClick($('[rotate-on-click]'));
app.directive('rotateOnClick', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var deg = 0;
element.bind('click', function() {
deg+= parseInt(attrs.rotateOnClick, 10);
element.css({
webkitTransform: 'rotate('+deg+'deg)',
mozTransform: 'rotate('+deg+'deg)',
msTransform: 'rotate('+deg+'deg)',
oTransform: 'rotate('+deg+'deg)',
transform: 'rotate('+deg+'deg)'
});
});
}
};
});
Pretty light, VERY clean and that's just a simple manipulation! In my opinion, the angular approach wins in all regards, especially how the functionality is abstracted away and the dom manipulation is declared in the DOM. The functionality is hooked onto the element via an html attribute, so there is no need to query the DOM via a selector, and we've got two nice closures - one closure for the directive factory where variables are shared across all usages of the directive, and one closure for each usage of the directive in the link
function (or compile
function).
Two-way data binding and directives for DOM manipulation are only the start of what makes Angular awesome. Angular promotes all code being modular, reusable, and easily testable and also includes a single-page app routing system. It is important to note that jQuery is a library of commonly needed convenience/cross-browser methods, but Angular is a full featured framework for creating single page apps. The angular script actually includes its own "lite" version of jQuery so that some of the most essential methods are available. Therefore, you could argue that using Angular IS using jQuery (lightly), but Angular provides much more "magic" to help you in the process of creating apps.
This is a great post for more related information: How do I “think in AngularJS” if I have a jQuery background?
The above points are aimed at the OP's specific concerns. I'll also give an overview of the other important differences. I suggest doing additional reading about each topic as well.
Angular is a framework, jQuery is a library. Frameworks have their place and libraries have their place. However, there is no question that a good framework has more power in writing an application than a library. That's exactly the point of a framework. You're welcome to write your code in plain JS, or you can add in a library of common functions, or you can add a framework to drastically reduce the code you need to accomplish most things. Therefore, a more appropriate question is:
Good frameworks can help architect your code so that it is modular (therefore reusable), DRY, readable, performant and secure. jQuery is not a framework, so it doesn't help in these regards. We've all seen the typical walls of jQuery spaghetti code. This isn't jQuery's fault - it's the fault of developers that don't know how to architect code. However, if the devs did know how to architect code, they would end up writing some kind of minimal "framework" to provide the foundation (achitecture, etc) I discussed a moment ago, or they would add something in. For example, you might add RequireJS to act as part of your framework for writing good code.
Here are some things that modern frameworks are providing:
Before I further discuss Angular, I'd like to point out that Angular isn't the only one of its kind. Durandal, for example, is a framework built on top of jQuery, Knockout, and RequireJS. Again, jQuery cannot, by itself, provide what Knockout, RequireJS, and the whole framework built on top them can. It's just not comparable.
If you need to destroy a planet and you have a Death Star, use the Death star.
Building on my previous points about what frameworks provide, I'd like to commend the way that Angular provides them and try to clarify why this is matter of factually superior to jQuery alone.
In my above example, it is just absolutely unavoidable that jQuery has to hook onto the DOM in order to provide functionality. That means that the view (html) is concerned about functionality (because it is labeled with some kind of identifier - like "image slider") and JavaScript is concerned about providing that functionality. Angular eliminates that concept via abstraction. Properly written code with Angular means that the view is able to declare its own behavior. If I want to display a clock:
<clock></clock>
Done.
Yes, we need to go to JavaScript to make that mean something, but we're doing this in the opposite way of the jQuery approach. Our Angular directive (which is in it's own little world) has "augumented" the html and the html hooks the functionality into itself.
Angular gives you a straightforward way to structure your code. View things belong in the view (html), augmented view functionality belongs in directives, other logic (like ajax calls) and functions belong in services, and the connection of services and logic to the view belongs in controllers. There are some other angular components as well that help deal with configuration and modification of services, etc. Any functionality you create is automatically available anywhere you need it via the Injector subsystem which takes care of Dependency Injection throughout the application. When writing an application (module), I break it up into other reusable modules, each with their own reusable components, and then include them in the bigger project. Once you solve a problem with Angular, you've automatically solved it in a way that is useful and structured for reuse in the future and easily included in the next project. A HUGE bonus to all of this is that your code will be much easier to test.
THANK GOODNESS. The aforementioned jQuery spaghetti code resulted from a dev that made something "work" and then moved on. You can write bad Angular code, but it's much more difficult to do so, because Angular will fight you about it. This means that you have to take advantage (at least somewhat) to the clean architecture it provides. In other words, it's harder to write bad code with Angular, but more convenient to write clean code.
Angular is far from perfect. The web development world is always growing and changing and there are new and better ways being put forth to solve problems. Facebook's React and Flux, for example, have some great advantages over Angular, but come with their own drawbacks. Nothing's perfect, but Angular has been and is still awesome for now. Just as jQuery once helped the web world move forward, so has Angular, and so will many to come.
There's a kind of hack-tastic way to do it if you have php enabled on your server. Change this line:
url: 'http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml',
to this line:
url: '/path/to/phpscript.php',
and then in the php script (if you have permission to use the file_get_contents() function):
<?php
header('Content-type: application/xml');
echo file_get_contents("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");
?>
Php doesn't seem to mind if that url is from a different origin. Like I said, this is a hacky answer, and I'm sure there's something wrong with it, but it works for me.
Edit: If you want to cache the result in php, here's the php file you would use:
<?php
$cacheName = 'somefile.xml.cache';
// generate the cache version if it doesn't exist or it's too old!
$ageInSeconds = 3600; // one hour
if(!file_exists($cacheName) || filemtime($cacheName) > time() + $ageInSeconds) {
$contents = file_get_contents('http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml');
file_put_contents($cacheName, $contents);
}
$xml = simplexml_load_file($cacheName);
header('Content-type: application/xml');
echo $xml;
?>
Caching code take from here.
You could pull a branch to a branch with the following commands.
git pull {repo} {remotebranchname}:{localbranchname}
git pull origin xyz:xyz
When you are on the master branch you also could first checkout a branch like:
git checkout -b xyz
This creates a new branch, "xyz", from the master and directly checks it out.
Then you do:
git pull origin xyz
This pulls the new branch to your local xyz
branch.
Presumably from this site:
Internal Fragmentation Internal fragmentation occurs when the memory allocator leaves extra space empty inside of a block of memory that has been allocated for a client. This usually happens because the processor’s design stipulates that memory must be cut into blocks of certain sizes -- for example, blocks may be required to be evenly be divided by four, eight or 16 bytes. When this occurs, a client that needs 57 bytes of memory, for example, may be allocated a block that contains 60 bytes, or even 64. The extra bytes that the client doesn’t need go to waste, and over time these tiny chunks of unused memory can build up and create large quantities of memory that can’t be put to use by the allocator. Because all of these useless bytes are inside larger memory blocks, the fragmentation is considered internal.
External Fragmentation External fragmentation happens when the memory allocator leaves sections of unused memory blocks between portions of allocated memory. For example, if several memory blocks are allocated in a continuous line but one of the middle blocks in the line is freed (perhaps because the process that was using that block of memory stopped running), the free block is fragmented. The block is still available for use by the allocator later if there’s a need for memory that fits in that block, but the block is now unusable for larger memory needs. It cannot be lumped back in with the total free memory available to the system, as total memory must be contiguous for it to be useable for larger tasks. In this way, entire sections of free memory can end up isolated from the whole that are often too small for significant use, which creates an overall reduction of free memory that over time can lead to a lack of available memory for key tasks.
Date.parse
recognizes only specific formats, and you don't have the option of telling it what your input format is. In this case it thinks that the input is in the format mm/dd/yyyy
, so the result is wrong.
To fix this, you need either to parse the input yourself (e.g. with String.split
) and then manually construct a Date
object, or use a more full-featured library such as datejs.
Example for manual parsing:
var input = $('#' + controlName).val();
var parts = str.split("/");
var d1 = new Date(Number(parts[2]), Number(parts[1]) - 1, Number(parts[0]));
Example using date.js:
var input = $('#' + controlName).val();
var d1 = Date.parseExact(input, "d/M/yyyy");
(Adding response on old q as this is the top result on google)
I tried yielding a new state in the callback within a bloc, and it didn't work. Tried with Timer and Future.delayed.
However, what did work was...
await Future.delayed(const Duration(milliseconds: 500));
yield newState;
Awaiting an empty future then running the function afterwards.
I think what @korona meant was since it's just a C API, you can consume it from C# directly with a heck of a lot of typing like this:
[DllImport("opengl32")]
public static extern void glVertex3f(float x, float y, float z);
You unfortunately would need to do this for every single OpenGL function you call, and is basically what Tao has done for you.
Why not run something like Nexus, your own maven repo that you can upload 3rd party proprietary jar files, and also proxy other public repositories, to save on bandwith?
This also has some good reasons to run your own maven repository manager.
DISCLAIMER: THIS WILL DELETE ALL OF YOUR ECLIPSE WORKSPACE SETTINGS AND YOU WILL HAVE TO RE-IMPORT ALL YOUR PROJECTS, THERE ARE LESS DESTRUCTIVE ANSWERS HERE
Try the following:
Delete the .metadata folder in your local workspace (this is what worked for me). It seems that it contains a .LOCK file that if not properly closed, prevents eclipse from starting properly. On Unix based systems you can type following on command line;
rm -r workspace/.metadata
Delete your .eclipse directory in your home directory. Launch eclipse. If that doesn't work,
Open eclipse under another user account. If it loads, you know the problem is with your account, not your eclipse installation.
Use padding
on the cells and border-spacing
on the table. The former will give you cellpadding while the latter will give you cellspacing.
table { border-spacing: 5px; } /* cellspacing */
th, td { padding: 5px; } /* cellpadding */
Depending on how you want to run it:
const reduced = (array, val) => { // self explanatory
return array.filter((element) => element === val).length;
}
console.log(reduced([1, 2, 3, 5, 2, 8, 9, 2], 2));
// 3
const reducer = (array) => { // array to set > set.forEach > map.set
const count = new Map();
const values = new Set(array);
values.forEach((element)=> {
count.set(element, array.filter((arrayElement) => arrayElement === element).length);
});
return count;
}
console.log(reducer([1, 2, 3, 5, 2, 8, 9, 2]));
// Map(6) {1 => 1, 2 => 3, 3 => 1, 5 => 1, 8 => 1, …}
Here is an answer for Python 3.8 and OpenPyXL 3.0.0.
I tried to avoid using the get_column_letter
function but failed.
This solution uses the newly introduced assignment expressions aka "walrus operator":
import openpyxl
from openpyxl.utils import get_column_letter
workbook = openpyxl.load_workbook("myxlfile.xlsx")
worksheet = workbook["Sheet1"]
MIN_WIDTH = 10
for i, column_cells in enumerate(worksheet.columns, start=1):
width = (
length
if (length := max(len(str(cell_value) if (cell_value := cell.value) is not None else "")
for cell in column_cells)) >= MIN_WIDTH
else MIN_WIDTH
)
worksheet.column_dimensions[get_column_letter(i)].width = width
SQL Server recognizes 'TRUE'
and 'FALSE'
as bit
values. So, use a bit
data type!
declare @var bit
set @var = 'true'
print @var
That returns 1
.
List<string> lines = new List<string>();
using (var sr = new StreamReader("file.txt"))
{
while (sr.Peek() >= 0)
lines.Add(sr.ReadLine());
}
i would suggest this... of Groo's answer.
You need to use the autoGenerate
property
Your primary key annotation should be like this:
@PrimaryKey(autoGenerate = true)
Reference for PrimaryKey.
I know this is old but I just ran into this problem and none of the answers are suitable. nickf's solution works but it requires javascript. The best way is to disable the field and still pass the value is to use a hidden input field to pass the value to the form. For example,
<input type="text" value="22.2222" disabled="disabled" />
<input type="hidden" name="lat" value="22.2222" />
This way the value is passed but the user sees the greyed out field. The readonly attribute does not gray it out.
The output looks correct to me:
Invalid JavaScript code: sun.org.mozilla.javascript.internal.EvaluatorException: missing } after property list (<Unknown source>) in <Unknown source>; at line number 1
I think Invalid Javascript code: ..
is the start of the exception message.
Normally the stacktrace isn't returned with the message:
try {
throw new RuntimeException("hu?\ntrace-line1\ntrace-line2");
} catch (Exception e) {
System.out.println(e.getMessage()); // prints "hu?"
}
So maybe the code you are calling catches an exception and rethrows a ScriptException
. In this case maybe e.getCause().getMessage()
can help you.
Try this:
CSS
.style1{
background-color:red;
color:white;
font-size:44px;
}
HTML
<div id="foo">hello world!</div>
<img src="zoom.png" onclick="myFunction()" />
Javascript
function myFunction()
{
document.getElementById('foo').setAttribute("class", "style1");
}
As far as I know the permission system in Linux is set up in such a way to prevent exactly what you are trying to accomplish.
I think the best you can do is to give your Linux user a custom unzip one-liner to run on the prompt:
unzip zip_name.zip && chmod +x script_name.sh
If there are multiple scripts that you need to give execute permission to, write a grant_perms.sh
as follows:
#!/bin/bash
# file: grant_perms.sh
chmod +x script_1.sh
chmod +x script_2.sh
...
chmod +x script_n.sh
(You can put the scripts all on one line for chmod, but I found separate lines easier to work with in vim and with shell script commands.)
And now your unzip one-liner becomes:
unzip zip_name.zip && source grant_perms.sh
Note that since you are using source
to run grant_perms.sh
, it doesn't need execute permission
Assuming that create
and destroy
are free functions (which seems to be the case from the OP's code snippet) with the following signatures:
Bar* create();
void destroy(Bar*);
You can write your class Foo
like this
class Foo {
std::unique_ptr<Bar, void(*)(Bar*)> ptr_;
// ...
public:
Foo() : ptr_(create(), destroy) { /* ... */ }
// ...
};
Notice that you don't need to write any lambda or custom deleter here because destroy
is already a deleter.
SELECT DATEADD (DAY, -1 * (DAY(GETDATE()) - 1), GETDATE())
.....................................................................
If you dont want the time, then convert it to DATE or if want to make to time to 0:00:00, Convert to DATE and then back to DATETIME.
SELECT CONVERT (DATETIME,
CONVERT (DATE, DATEADD (DAY, -1 * (DAY(GETDATE()) - 1),
GETDATE())))
Change GETDATE() to the date you want
You need to check out the attr
method in the jQuery docs. You are misusing it. What you are doing within the if statements simply replaces all image tags src
with the string specified in the 2nd parameter.
A better way to approach replacing a series of images source would be to loop through each and check it's source.
Example:
$('img').each(function () {
var curSrc = $(this).attr('src');
if ( curSrc === 'http://example.com/smith.gif' ) {
$(this).attr('src', 'http://example.com/johnson.gif');
}
if ( curSrc === 'http://example.com/williams.gif' ) {
$(this).attr('src', 'http://example.com/brown.gif');
}
});
Is this what you had in mind?
$("document").ready( function() {
// do your stuff
}
Under Windows 7, open the Event Viewer. You can do this the way Gishu suggested for XP, typing eventvwr
from the command line, or by opening the Control Panel, selecting System and Security, then Administrative Tools and finally Event Viewer. It may require UAC approval or an admin password.
In the left pane, expand Windows Logs and then System. You can filter the logs with Filter Current Log... from the Actions pane on the right and selecting "Service Control Manager." Or, depending on why you want this information, you might just need to look through the Error entries.
The actual log entry pane (not shown) is pretty user-friendly and self-explanatory. You'll be looking for messages like the following:
"The Praxco Assistant service entered the stopped state."
"The Windows Image Acquisition (WIA) service entered the running state."
"The MySQL service terminated unexpectedly. It has done this 3 time(s)."
SELECT ..., CONCAT( 'category_id=', tableOne.category_id) as query2 FROM tableOne
LEFT JOIN tableTwo
ON tableTwo.query = query2
You can use verbatim literals:
const string test = @"Test
123
456
";
But the indentation of the 1st line is tricky/ugly.
Send XML requests with the raw
data type, then set the Content-Type to text/xml
.
After creating a request, use the dropdown to change the request type to POST.
Open the Body tab and check the data type for raw.
Open the Content-Type selection box that appears to the right and select either XML (application/xml) or XML (text/xml)
Enter your raw XML data into the input field below
Click Send to submit your XML Request to the specified server.
I had same problem after updating java. Then I paste
-vm
C:\Program Files\Java\jre6\bin\javaw.exe
to show the path of javaw.exe
in eclipse.ini
file.
Hope this will help you.
You would want and
instead of &&
.
<div style="position: absolute; overflow: hidden; left: 0px; top: 0px; border: solid 2px #555; width:594px; height:332px;">
<div style="overflow: hidden; margin-top: -100px; margin-left: -25px;">
</div>
<iframe src="http://example.com/" scrolling="no" style="height: 490px; border: 0px none; width: 619px; margin-top: -60px; margin-left: -24px; ">
</iframe>
</div>
</div>
timeobj = datetime.datetime.strptime(my_time, '%Y-%m-%d %I:%M:%S')
File "/usr/lib/python2.7/_strptime.py", line 335, in _strptime
data_string[found.end():])
ValueError: unconverted data remains:
In my case, the problem was an extra space in the input date string. So I used strip()
and it started to work.
You may also use math.log1p
.
According to the official documentation :
math.log1p(x)
Return the natural logarithm of 1+x (base e). The result is calculated in a way which is accurate for x near zero.
You may convert back to the original value using math.expm1
which returns e
raised to the power x, minus 1.
look at the following program for complete conversion concept
class typetest{
public static void main(String args[]){
byte a=1,b=2;
char c=1,d='b';
short e=3,f=4;
int g=5,h=6;
float i;
double k=10.34,l=12.45;
System.out.println("value of char variable c="+c);
// if we assign an integer value in char cariable it's possible as above
// but it's not possible to assign int value from an int variable in char variable
// (d=g assignment gives error as incompatible type conversion)
g=b;
System.out.println("char to int conversion is possible");
k=g;
System.out.println("int to double conversion is possible");
i=h;
System.out.println("int to float is possible and value of i = "+i);
l=i;
System.out.println("float to double is possible");
}
}
hope ,it will help at least something
I got it. This is very simple. Using the class bg
you can achieve this easily.
Let me show you:
<nav class="navbar navbar-expand-lg navbar-dark navbar-full bg-primary"></nav>
This gives you the default blue navbar
If you want to change your favorite color, then simply use the style tag within the nav
:
<nav class="navbar navbar-expand-lg navbar-dark navbar-full" style="background-color: #FF0000">
This is another, though not necessarily "better", way:
Determining Your Current Version
To determine which Oracle client version you have installed on your pc, run sql
*
plus to connect to the DW. The folder names may vary somewhat based on your Oracle setup but should be similar. To run sql*
plus choosestart > programs > Oracle > Oracle - OUDWclient > Application Development > sqlplus
. Enter your DW user name, password, and 'ordj' for the host name or service name. This should connect you to the DW via sqlplus. At this point, you could write your own sql statements to pull information from the DW (if you knew sql). The Oracle client version can be determined in the first line - 'SQL*Plus: Release 10.2.0.1.0'.
[Reference] Oracle Client Information http://www.ohio.edu/technology
Just for the fun of it, here are two ways that have not been explored:
substr($url, strpos($s, '/', 8), -4)
Or:
substr($s, strpos($s, '/', 8), -strlen($s) + strrpos($s, '.'))
Based on the idea that HTTP schemes http://
and https://
are at most 8 characters, so typically it suffices to find the first slash from the 9th position onwards. If the extension is always .php
the first code will work, otherwise the other one is required.
For a pure regular expression solution you can break the string down like this:
~^(?:[^:/?#]+:)?(?://[^/?#]*)?([^?#]*)~
^
The path portion would be inside the first memory group (i.e. index 1), indicated by the ^
in the line underneath the expression. Removing the extension can be done using pathinfo()
:
$parts = pathinfo($matches[1]);
echo $parts['dirname'] . '/' . $parts['filename'];
You can also tweak the expression to this:
([^?#]*?)(?:\.[^?#]*)?(?:\?|$)
This expression is not very optimal though, because it has some back tracking in it. In the end I would go for something less custom:
$parts = pathinfo(parse_url($url, PHP_URL_PATH));
echo $parts['dirname'] . '/' . $parts['filename'];
If you want the actual HTTP Host header, see Daniel Roseman's comment on @Phsiao's answer. The other alternative is if you're using the contrib.sites framework, you can set a canonical domain name for a Site in the database (mapping the request domain to a settings file with the proper SITE_ID is something you have to do yourself via your webserver setup). In that case you're looking for:
from django.contrib.sites.models import Site
current_site = Site.objects.get_current()
current_site.domain
you'd have to put the current_site object into a template context yourself if you want to use it. If you're using it all over the place, you could package that up in a template context processor.
You have some syntax issues with your script. Here is a fixed version:
#!/bin/bash
if [ "$seconds" -eq 0 ]; then
timezone_string="Z"
elif [ "$seconds" -gt 0 ]; then
timezone_string=$(printf "%02d:%02d" $((seconds/3600)) $(((seconds / 60) % 60)))
else
echo "Unknown parameter"
fi
You are misusing the API.
Here's the situation: in ASP.NET, only one thread can handle a request at a time. You can do some parallel processing if necessary (borrowing additional threads from the thread pool), but only one thread would have the request context (the additional threads do not have the request context).
This is managed by the ASP.NET SynchronizationContext
.
By default, when you await
a Task
, the method resumes on a captured SynchronizationContext
(or a captured TaskScheduler
, if there is no SynchronizationContext
). Normally, this is just what you want: an asynchronous controller action will await
something, and when it resumes, it resumes with the request context.
So, here's why test5
fails:
Test5Controller.Get
executes AsyncAwait_GetSomeDataAsync
(within the ASP.NET request context).AsyncAwait_GetSomeDataAsync
executes HttpClient.GetAsync
(within the ASP.NET request context).HttpClient.GetAsync
returns an uncompleted Task
.AsyncAwait_GetSomeDataAsync
awaits the Task
; since it is not complete, AsyncAwait_GetSomeDataAsync
returns an uncompleted Task
.Test5Controller.Get
blocks the current thread until that Task
completes.Task
returned by HttpClient.GetAsync
is completed.AsyncAwait_GetSomeDataAsync
attempts to resume within the ASP.NET request context. However, there is already a thread in that context: the thread blocked in Test5Controller.Get
.Here's why the other ones work:
test1
, test2
, and test3
): Continuations_GetSomeDataAsync
schedules the continuation to the thread pool, outside the ASP.NET request context. This allows the Task
returned by Continuations_GetSomeDataAsync
to complete without having to re-enter the request context.test4
and test6
): Since the Task
is awaited, the ASP.NET request thread is not blocked. This allows AsyncAwait_GetSomeDataAsync
to use the ASP.NET request context when it is ready to continue.And here's the best practices:
async
methods, use ConfigureAwait(false)
whenever possible. In your case, this would change AsyncAwait_GetSomeDataAsync
to be var result = await httpClient.GetAsync("http://stackoverflow.com", HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);
Task
s; it's async
all the way down. In other words, use await
instead of GetResult
(Task.Result
and Task.Wait
should also be replaced with await
).That way, you get both benefits: the continuation (the remainder of the AsyncAwait_GetSomeDataAsync
method) is run on a basic thread pool thread that doesn't have to enter the ASP.NET request context; and the controller itself is async
(which doesn't block a request thread).
More information:
async
/await
intro post, which includes a brief description of how Task
awaiters use SynchronizationContext
.SynchronizationContext
restricts the request context to just one thread at a time.Update 2012-07-13: Incorporated this answer into a blog post.
I used the below. The genre element will start where the DJ element ends,
<div>
<div style="width:50%; float:left">DJ</div>
<div>genre</div>
</div>
pardon the inline css.
It's quite simple, use
Long.valueOf(String s);
For example:
String s;
long l;
Scanner sc=new Scanner(System.in);
s=sc.next();
l=Long.valueOf(s);
System.out.print(l);
You're done!!!
Masking means to keep/change/remove a desired part of information. Lets see an image-masking operation; like- this masking operation is removing any thing that is not skin-
We are doing AND operation in this example. There are also other masking operators- OR, XOR.
Bit-Masking means imposing mask over bits. Here is a bit-masking with AND-
1 1 1 0 1 1 0 1 [input] (&) 0 0 1 1 1 1 0 0 [mask] ------------------------------ 0 0 1 0 1 1 0 0 [output]
So, only the middle 4 bits (as these bits are 1
in this mask) remain.
Lets see this with XOR-
1 1 1 0 1 1 0 1 [input] (^) 0 0 1 1 1 1 0 0 [mask] ------------------------------ 1 1 0 1 0 0 0 1 [output]
Now, the middle 4 bits are flipped (1
became 0
, 0
became 1
).
So, using bit-mask we can access individual bits [examples]. Sometimes, this technique may also be used for improving performance. Take this for example-
bool isOdd(int i) {
return i%2;
}
This function tells if an integer is odd/even. We can achieve the same result with more efficiency using bit-mask-
bool isOdd(int i) {
return i&1;
}
Short Explanation: If the least significant bit of a binary number is 1
then it is odd; for 0
it will be even. So, by doing AND with 1
we are removing all other bits except for the least significant bit i.e.:
55 -> 0 0 1 1 0 1 1 1 [input] (&) 1 -> 0 0 0 0 0 0 0 1 [mask] --------------------------------------- 1 <- 0 0 0 0 0 0 0 1 [output]
signingConfigs should be before buildTypes
signingConfigs {
debug {
storeFile file("debug.keystore")
}
myConfig {
storeFile file("other.keystore")
storePassword "android"
keyAlias "androidotherkey"
keyPassword "android"
}
}
buildTypes {
bar {
debuggable true
jniDebugBuild true
signingConfig signingConfigs.debug
}
foo {
debuggable false
jniDebugBuild false
signingConfig signingConfigs.myConfig
}
}
It is ugly and performs badly, but technically this works on any table with at least one unique field AND works in SQL 2000.
SELECT (SELECT COUNT(*) FROM myTable T1 WHERE T1.UniqueField<=T2.UniqueField) as RowNum, T2.OtherField
FROM myTable T2
ORDER By T2.UniqueField
Note: If you use this approach and add a WHERE clause to the outer SELECT, you have to added it to the inner SELECT also if you want the numbers to be continuous.
For example, to execute following with command prompt or BATCH file we can use this:
C:\Python27\python.exe "C:\Program files(x86)\dev_appserver.py" --host 0.0.0.0 --post 8080 "C:\blabla\"
Same thing to do with Python, we can do this:
subprocess.Popen(['C:/Python27/python.exe', 'C:\\Program files(x86)\\dev_appserver.py', '--host', '0.0.0.0', '--port', '8080', 'C:\\blabla'], shell=True)
or
subprocess.Popen(['C:/Python27/python.exe', 'C:/Program files(x86)/dev_appserver.py', '--host', '0.0.0.0', '--port', '8080', 'C:/blabla'], shell=True)
There is probably another table with a foreign key referencing the primary key you are trying to change.
To find out which table caused the error you can run SHOW ENGINE INNODB
STATUS
and then look at the LATEST FOREIGN KEY ERROR
section
Use SHOW CREATE TABLE categories to show the name of constraint.
Most probably it will be categories_ibfk_1
Use the name to drop the foreign key first and the column then:
ALTER TABLE categories DROP FOREIGN KEY categories_ibfk_1;
ALTER TABLE categories DROP COLUMN assets_id;
In my case , I had removed gradlew and gradle folders from project. Reran clean build tasks through "Run Gradle Task" from Gradle Projects window in intellij
You could create many tasks like:
List<Task> TaskList = new List<Task>();
foreach(...)
{
var LastTask = new Task(SomeFunction);
LastTask.Start();
TaskList.Add(LastTask);
}
Task.WaitAll(TaskList.ToArray());
Just to add. Another disadvantage would be, .inc files are not recognized by IDE thus, you could not take advantage of auto-complete or code prediction features.
To those still having problems, I solved it this way:
List<Item> newItems = databaseHandler.getItems();
ListArrayAdapter.clear();
ListArrayAdapter.addAll(newItems);
ListArrayAdapter.notifyDataSetChanged();
databaseHandler.close();
I first cleared the data from the adapter, then added the new collection of items, and only then set notifyDataSetChanged();
This was not clear for me at first, so I wanted to point this out. Take note that without calling notifyDataSetChanged()
the view won't be updated.
And if you would like to use an existing context, rather than a new context which would be loaded from xml configuration by org.springframework.web.context.ContextLoaderListener, then see -> https://stackoverflow.com/a/40694787/3004747
If you are using prototype.js then you can do this:
transport_select.observe('change', function(){
toggleSelect(transport_select_id)
})
This eliminate (as hope) the problem in cross-browsers
After reading the documentation: http://momentjs.com/docs/#/displaying/difference/, you have to consider the diff
function like a minus operator.
// today < future (31/01/2014)
today.diff(future) // today - future < 0
future.diff(today) // future - today > 0
Therefore, you have to reverse your condition.
If you want to check that all is fine, you can add an extra parameter to the function:
moment().diff(SpecialTo, 'days') // -8 (days)
Check out https://github.com/shaneharter/PHP-Daemon
This is an object-oriented daemon library. It has built-in support for things like logging and error recovery, and it has support for creating background workers.
You might actually look into the internationally standardized format E.164, recommended by Twilio for example (who have a service and an API for sending SMS or phone-calls via REST requests).
This is likely to be the most universal way to store phone numbers, in particular if you have international numbers work with.
You can use phonenumber_field
library. It is port of Google's libphonenumber library, which powers Android's phone number handling
https://github.com/stefanfoulis/django-phonenumber-field
In model:
from phonenumber_field.modelfields import PhoneNumberField
class Client(models.Model, Importable):
phone = PhoneNumberField(null=False, blank=False, unique=True)
In form:
from phonenumber_field.formfields import PhoneNumberField
class ClientForm(forms.Form):
phone = PhoneNumberField()
Get phone as string from object field:
client.phone.as_e164
Normolize phone string (for tests and other staff):
from phonenumber_field.phonenumber import PhoneNumber
phone = PhoneNumber.from_string(phone_number=raw_phone, region='RU').as_e164
One note for your model: E.164 numbers have a max character length of 15.
To validate, you can employ some combination of formatting and then attempting to contact the number immediately to verify.
I believe I used something like the following on my django project:
class ReceiverForm(forms.ModelForm):
phone_number = forms.RegexField(regex=r'^\+?1?\d{9,15}$',
error_message = ("Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed."))
EDIT
It appears that this post has been useful to some folks, and it seems worth it to integrate the comment below into a more full-fledged answer. As per jpotter6, you can do something like the following on your models as well:
models.py:
from django.core.validators import RegexValidator
class PhoneModel(models.Model):
...
phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.")
phone_number = models.CharField(validators=[phone_regex], max_length=17, blank=True) # validators should be a list
If speed is critical, you might want to look for the Aho-Corasick algorithm for sets of patterns.
It's a trie with failure links, that is, complexity is O(n+m+k), where n is the length of the input text, m the cumulative length of the patterns and k the number of matches. You just have to modify the algorithm to terminate after the first match is found.
I solved this error with clearing cache and restarting chrome. Hope they will fix it in ver 40.
Using C# 7 (.NET Framework 4.6.2) you can write an IsNumeric function as a one-liner:
public bool IsNumeric(string val) => int.TryParse(val, out int result);
Note that the function above will only work for integers (Int32). But you can implement corresponding functions for other numeric data types, like long, double, etc.
If your intention was to find a way to represent null in an enumeration of singleton objects, then it's a bad idea to (de)reference null (it C++11, nullptr).
Why not declare static singleton object that represents NULL within the class as follows and add a cast-to-pointer operator that returns nullptr ?
Edit: Corrected several mistypes and added if-statement in main() to test for the cast-to-pointer operator actually working (which I forgot to.. my bad) - March 10 2015 -
// Error.h
class Error {
public:
static Error& NOT_FOUND;
static Error& UNKNOWN;
static Error& NONE; // singleton object that represents null
public:
static vector<shared_ptr<Error>> _instances;
static Error& NewInstance(const string& name, bool isNull = false);
private:
bool _isNull;
Error(const string& name, bool isNull = false) : _name(name), _isNull(isNull) {};
Error() {};
Error(const Error& src) {};
Error& operator=(const Error& src) {};
public:
operator Error*() { return _isNull ? nullptr : this; }
};
// Error.cpp
vector<shared_ptr<Error>> Error::_instances;
Error& Error::NewInstance(const string& name, bool isNull = false)
{
shared_ptr<Error> pNewInst(new Error(name, isNull)).
Error::_instances.push_back(pNewInst);
return *pNewInst.get();
}
Error& Error::NOT_FOUND = Error::NewInstance("NOT_FOUND");
//Error& Error::NOT_FOUND = Error::NewInstance("UNKNOWN"); Edit: fixed
//Error& Error::NOT_FOUND = Error::NewInstance("NONE", true); Edit: fixed
Error& Error::UNKNOWN = Error::NewInstance("UNKNOWN");
Error& Error::NONE = Error::NewInstance("NONE");
// Main.cpp
#include "Error.h"
Error& getError() {
return Error::UNKNOWN;
}
// Edit: To see the overload of "Error*()" in Error.h actually working
Error& getErrorNone() {
return Error::NONE;
}
int main(void) {
if(getError() != Error::NONE) {
return EXIT_FAILURE;
}
// Edit: To see the overload of "Error*()" in Error.h actually working
if(getErrorNone() != nullptr) {
return EXIT_FAILURE;
}
}
I follow it extremely rigorously. The only god before PEP-8 is existing code bases.
Maybe You should try scrollIntoView.
document.getElementById('id').scrollIntoView();
This will scroll to your Element.
We could look at error object for a property code
that mentions the possible system error and in cases of ETIMEDOUT
where a network call fails, act accordingly.
if (err.code === 'ETIMEDOUT') {
console.log('My dish error: ', util.inspect(err, { showHidden: true, depth: 2 }));
}
The @japf answer above is working fine and in my case I wanted to change the mouse cursor from a Spinning Wheel back to the normal Arrow once the CEF Browser finished loading the page. In case it can help someone, here is the code:
private void Browser_LoadingStateChanged(object sender, CefSharp.LoadingStateChangedEventArgs e) {
if (!e.IsLoading) {
// set the cursor back to arrow
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background,
new Action(() => Mouse.OverrideCursor = Cursors.Arrow));
}
}
If your having trouble connecting, most likely the problem is that you haven't yet enabled the TCP/IP listener on port 1433. A quick "netstat -an" command will tell you if its listening. By default, SQL server doesn't enable this after installation.
Also, you need to set a password on the "sa" account and also ENABLE the "sa" account (if you plan to use that account to connect with).
Obviously, this also means you need to enable "mixed mode authentication" on your MSSQL node.
The jQuery plugin is probably the best option. http://farinspace.com/jquery-scrollable-table-plugin/
To fixing header you can check this post
Fixing Header of GridView or HtmlTable (there might be issue that this should work in IE only)
CSS for fixing header
div#gridPanel
{
width:900px;
overflow:scroll;
position:relative;
}
div#gridPanel th
{
top: expression(document.getElementById("gridPanel").scrollTop-2);
left:expression(parentNode.parentNode.parentNode.parentNode.scrollLeft);
position: relative;
z-index: 20;
}
<div height="200px" id="gridPanel" runat="server" scrollbars="Auto" width="100px">
table..
</div>
or
Very good post is here for this
How to Freeze Columns Using JavaScript and HTML.
or
No its not possible but you can make use of div and put table in div
<div style="height: 100px; overflow: auto">
<table style="height: 500px;">
...
</table>
</div>
To better understand the type conversion, look at the code below:
package main
import "fmt"
func foo(a interface{}) {
fmt.Println(a.(int)) // conversion of interface into int
}
func main() {
var a int = 10
foo(a)
}
This code executes perfectly and converts interface type to int type
For an expression x of interface type and a type T, the primary expression x.(T) asserts that x is not nil and that the value stored in x is of type T. The notation x.(T) is called a type assertion. More precisely, if T is not an interface type, x.(T) asserts that the dynamic type of x is identical to the type T. In this case, T must implement the (interface) type of x; otherwise the type assertion is invalid since it is not possible for x to store a value of type T. If T is an interface type, x.(T) asserts that the dynamic type of x implements the interface T.
Going back to your code, this
iAreaId := val.(int)
should work good. If you want to check error occured while conversion, you can also re-write above line as
iAreaId, ok := val.(int)
I was disappointed this issue still exist till today. As I have recently been trying to install vCD CLI on CentOS 8.1 and I was welcomed with the same error when tried to run it. The way I had to resolve it in my case is as follow:
As I have been doing this to create a different blogpost about how to install vCD CLI and VMware Container Service Extension. I have end up capturing the steps I used to fix the issue and put it in a separate blog post at:
I hope this helpful, as while the tips above had helped me get to a solution, I had to combine few of them and modify them a bit.
Under the TODOs, i am trying to implement your code in this posting. I am trying to take the large div on the left and make it change to reflect selections on the right. there are two selections, Ambient Temperature and Body Temperature
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title> Temperature Selection </title>_x000D_
<!-- css -->_x000D_
<link rel="stylesheet" href="bootstrap-3/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="css/main.css">_x000D_
_x000D_
<!-- end css -->_x000D_
<!-- Java script files -->_x000D_
<!-- Date.js date os javascript helper -->_x000D_
<script src="js/date.js"> </script>_x000D_
_x000D_
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->_x000D_
<script src="js/jquery-2.1.1.min.js"></script>_x000D_
_x000D_
<!-- Include all compiled plugins (below), or include individual files as needed -->_x000D_
<script src="bootstrap-3/js/bootstrap.min.js"> </script>_x000D_
<script src="js/library.js"> </script>_x000D_
<script src="js/sfds.js"> </script>_x000D_
_x000D_
<script src="js/main.js"> </script>_x000D_
_x000D_
<!-- End Java script files -->_x000D_
_x000D_
<!--TODO: need to integrate this code into the project:-->_x000D_
<script type="text/javascript">_x000D_
function changeImage(a) {_x000D_
document.getElementById("img").src=a;_x000D_
}_x000D_
</script>_x000D_
<script>_x000D_
_x000D_
_x000D_
$(document).ready(function() {_x000D_
_x000D_
$("#ambient").click(function(event){_x000D_
var $this= $(this);_x000D_
if($this.hasClass('clicked')){_x000D_
$this.removeClass('clicked');_x000D_
SFDS.setTemperatureType(0);_x000D_
$this.find('h2').text('Select Ambient Temperature 21 Degrees C');_x000D_
<!--added on 05/20/2015-->_x000D_
}else{_x000D_
SFDS.setTemperatureType(1);_x000D_
$this.addClass('clicked');_x000D_
$this.find('h2').text('Ambient Temperature 21 Degrees C Selected');_x000D_
_x000D_
_x000D_
}_x000D_
});_x000D_
_x000D_
$("#body").click(function(event){_x000D_
var $this= $(this);_x000D_
if($this.hasClass('clicked')){_x000D_
$this.removeClass('clicked');_x000D_
SFDS.setTemperatureType(0);_x000D_
$this.find('h2').text('Select Body Temperature 37 Degrees C');_x000D_
<!--added on 05/20/2015-->_x000D_
}else{_x000D_
SFDS.setTemperatureType(1);_x000D_
$this.addClass('clicked');_x000D_
$this.find('h2').text('Body Temperature 37 Degrees C Selected');_x000D_
_x000D_
_x000D_
}_x000D_
});_x000D_
_x000D_
_x000D_
_x000D_
});_x000D_
</script>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<div class="container-fluid">_x000D_
<header>_x000D_
<div class="row">_x000D_
<div class="col-xs-6">_x000D_
<div id="date"><span class="date_time"></span></div>_x000D_
</div>_x000D_
<div class="col-xs-6">_x000D_
<div id="time" class="text-right"><span class="date_time"></span></div>_x000D_
</div>_x000D_
</div>_x000D_
</header>_x000D_
<div class="row">_x000D_
<div class="col-md-offset-1 col-sm-3 col-xs-8 col-xs-offset-2 col-sm-offset-0">_x000D_
<div id="temperature" class="main_button center-block">_x000D_
<div class="large_circle_button"> _x000D_
<h2>Select<br/>Temperature</h2>_x000D_
<img class="center-block large_button_image" src="images/thermometer.png" alt=""> _x000D_
<!-- TODO <img src='images/dropsterilewater.png' onclick='changeImage("images/dropsterilewater.png");'>_x000D_
<img src='images/imagecansterilesaline.png' onclick='changeImage("images/imagecansterilesaline.png");'>-->_x000D_
</div>_x000D_
<h1></h1>_x000D_
</div>_x000D_
</div>_x000D_
<div class=" col-md-6 col-sm-offset-1 col-sm-8 col-xs-12">_x000D_
<div class="row">_x000D_
<div class="col-xs-12">_x000D_
<div id="ambient" class="large_rectangle_button">_x000D_
<div class="label_wrapper">_x000D_
<h2>Ambient<br/>Temperature<br/>21<sup>o</sup>C</h2>_x000D_
</div>_x000D_
<div class="image_wrapper">_x000D_
<img src="images/house.png" alt="" class="ambient_temp_image">_x000D_
</div>_x000D_
<img src="images/checkmark.png" class="button_checkmark" width="96" height="88">_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
<div class="col-xs-12">_x000D_
<div id="body" class="large_rectangle_button">_x000D_
<div class="label_wrapper">_x000D_
<h2>Body<br/>Temperature<br/>37<sup>o</sup>C</h2>_x000D_
</div>_x000D_
<div class="image_wrapper">_x000D_
<img src="images/bodytempman.png" alt="" class="body_temp_image">_x000D_
</div>_x000D_
<img src="images/checkmark.png" class="button_checkmark" width="96" height="88">_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
_x000D_
</div>_x000D_
<footer class="footer navbar-fixed-bottom">_x000D_
<div class="container-fluid">_x000D_
<div class="row cols-bottom">_x000D_
<div class="col-sm-3">_x000D_
<a href="main.html">_x000D_
<div class="small_circle_button"> _x000D_
<img src="images/buttonback.png" alt="back to home" class="settings"/> <!-- width="49" height="48" -->_x000D_
</div>_x000D_
</div></a><div class=" col-sm-6">_x000D_
<div id="stop_button" >_x000D_
<img src="images/stop.png" alt="stop" class="center-block stop_button" /> <!-- width="140" height="128" -->_x000D_
</div>_x000D_
_x000D_
</div><div class="col-sm-3">_x000D_
<div id="parker" class="pull-right">_x000D_
<img src="images/#" alt="logo" /> <!-- width="131" height="65" -->_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</footer>_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
Here is another method to iterate through an object.
var p = {_x000D_
"p1": "value1",_x000D_
"p2": "value2",_x000D_
"p3": "value3"_x000D_
};_x000D_
_x000D_
_x000D_
Object.keys(p).forEach(key => { console.log(key, p[key]) })
_x000D_
NoClassDefFoundError doesn't give much of a clue as to what went wrong inside the static block. It is good practice to always have a block like this inside of static { ... } initialization code:
static {
try {
... your init code here
} catch (Throwable t) {
LOG.error("Failure during static initialization", t);
throw t;
}
}