If you control the type being used as dynamic, couldn't you return a tuple instead of a value for every property access? Something like...
public class DynamicValue<T>
{
internal DynamicValue(T value, bool exists)
{
Value = value;
Exists = exists;
}
T Value { get; private set; }
bool Exists { get; private set; }
}
Possibly a naive implementation, but if you construct one of these internally each time and return that instead of the actual value, you can check Exists
on every property access and then hit Value
if it does with value being default(T)
(and irrelevant) if it doesn't.
That said, I might be missing some knowledge on how dynamic works and this might not be a workable suggestion.
Unless you unpack them, assets remain inside the apk. Accordingly, there isn't a path you can feed into a File. The path you've given in your question will work with/in a WebView, but I think that's a special case for WebView.
You'll need to unpack the file or use it directly.
If you have a Context, you can use context.getAssets().open("myfoldername/myfilename");
to open an InputStream on the file. With the InputStream you can use it directly, or write it out somewhere (after which you can use it with File).
This problem appear if two software use same port for connecting to the server
try to close the port by cmd according to your operating system
then reboot your Android studio or your Eclipse or your Software.
I wrote a class to normalize the data in my dictionary. The 'element' in the NormalizeData class below, needs to be of dict type. And you need to replace in the __iterate() with either your custom class object or any other object type that you would like to normalize.
class NormalizeData:
def __init__(self, element):
self.element = element
def execute(self):
if isinstance(self.element, dict):
self.__iterate()
else:
return
def __iterate(self):
for key in self.element:
if isinstance(self.element[key], <ClassName>):
self.element[key] = str(self.element[key])
node = NormalizeData(self.element[key])
node.execute()
By default, MomentJS parses in local time. If only a date string (with no time) is provided, the time defaults to midnight.
In your code, you create a local date and then convert it to the UTC timezone (in fact, it makes the moment instance switch to UTC mode), so when it is formatted, it is shifted (depending on your local time) forward or backwards.
If the local timezone is UTC+N (N being a positive number), and you parse a date-only string, you will get the previous date.
Here are some examples to illustrate it (my local time offset is UTC+3 during DST):
>>> moment('07-18-2013', 'MM-DD-YYYY').utc().format("YYYY-MM-DD HH:mm")
"2013-07-17 21:00"
>>> moment('07-18-2013 12:00', 'MM-DD-YYYY HH:mm').utc().format("YYYY-MM-DD HH:mm")
"2013-07-18 09:00"
>>> Date()
"Thu Jul 25 2013 14:28:45 GMT+0300 (Jerusalem Daylight Time)"
If you want the date-time string interpreted as UTC, you should be explicit about it:
>>> moment(new Date('07-18-2013 UTC')).utc().format("YYYY-MM-DD HH:mm")
"2013-07-18 00:00"
or, as Matt Johnson mentions in his answer, you can (and probably should) parse it as a UTC date in the first place using moment.utc()
and include the format string as a second argument to prevent ambiguity.
>>> moment.utc('07-18-2013', 'MM-DD-YYYY').format("YYYY-MM-DD HH:mm")
"2013-07-18 00:00"
To go the other way around and convert a UTC date to a local date, you can use the local()
method, as follows:
>>> moment.utc('07-18-2013', 'MM-DD-YYYY').local().format("YYYY-MM-DD HH:mm")
"2013-07-18 03:00"
You don't need to find the file.
Only write this instruction on terminal:
git config --global --edit
I'd be cautious as dismissing something as a bad idea because it is slow. If it is a part of the code that does not take much time to execute then the slowness is irrelevant. I just used the following code:
for (ic in 1:(dim(centroid)[2]))
{
cluster[[ic]]=matrix(,nrow=2,ncol=0)
}
# code to identify cluster=pindex[ip] to which to add the point
if(pdist[ip]>-1)
{
cluster[[pindex[ip]]]=cbind(cluster[[pindex[ip]]],points[,ip])
}
for a problem that ran in less than 1 second.
In java 8 you can also use a reducer, something like:
public static String join(List<String> strings, String joinStr) {
return strings.stream().reduce("", (prev, cur) -> prev += (cur + joinStr));
}
Glide version 4.6.1
Glide.with(context)
.load(url)
.apply(RequestOptions.bitmapTransform(new CircleCrop()))
.into(imageView);
You're giving parameters to your program instead to Java. Use
java -Dtest="true" -jar myApplication.jar
instead.
Consider using
"true".equalsIgnoreCase(System.getProperty("test"))
to avoid the NPE. But do not use "Yoda conditions" always without thinking, sometimes throwing the NPE is the right behavior and sometimes something like
System.getProperty("test") == null || System.getProperty("test").equalsIgnoreCase("true")
is right (providing default true). A shorter possibility is
!"false".equalsIgnoreCase(System.getProperty("test"))
but not using double negation doesn't make it less hard to misunderstand.
In my case I forgot to add .h and .m file in .podspecs file's "s.source_files" section.
after adding this in it work fine.
You are looking at the wrong documentation. The time
module has different documentation.
You can use the datetime
module strftime
like this:
>>> from datetime import datetime
>>>
>>> now = datetime.now()
>>> now.strftime("%H:%M:%S.%f")
'12:19:40.948000'
try this it work out for me perfectly go to project and right click on your java file at the right corner, go to properties, go to run, go to browse, and then select Main class. now you can run your program again.
Have you tried using the !important flag on the style? !important allows you to decide which style will win out. Also note !important will override inline styles as well.
#example p {
color: blue !important;
}
...
#example p {
color: red;
}
Another couple suggestions:
Add a span inside of the current. The inner most will win out. Although this could get pretty ugly.
<span class="style21">
<span style="position:absolute;top:432px;left:422px; color:Red" >relating to</span>
</span>
jQuery is also an option. The jQuery library will inject the style attribute in the targeted element.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js" type="text/javascript" ></script>
<script type="text/javascript">
$(document).ready(function() {
$("span").css("color", "#ff0000");
});
</script>
Hope this helps. CSS can be pretty frustrating at times.
Maybe will be useful for somebody. I had a little bit another requirement. Having list of objects A
from 3rd party remove all which have same A.b
field for same A.id
(multiple A
object with same A.id
in list). Stream partition answer by Tagir Valeev inspired me to use custom Collector
which returns Map<A.id, List<A>>
. Simple flatMap
will do the rest.
public static <T, K, K2> Collector<T, ?, Map<K, List<T>>> groupingDistinctBy(Function<T, K> keyFunction, Function<T, K2> distinctFunction) {
return groupingBy(keyFunction, Collector.of((Supplier<Map<K2, T>>) HashMap::new,
(map, error) -> map.putIfAbsent(distinctFunction.apply(error), error),
(left, right) -> {
left.putAll(right);
return left;
}, map -> new ArrayList<>(map.values()),
Collector.Characteristics.UNORDERED)); }
This REGEX is a patch from @Aamir answer that worked for me
/((?:(?:http?|ftp)[s]*:\/\/)?[a-z0-9-%\/\&=?\.]+\.[a-z]{2,4}\/?([^\s<>\#%"\,\{\}\\|\\\^\[\]`]+)?)/gi
It matches these URL formats
Oh you can Output a message when using QT += gui
and CONFIG += console
.
You need printf("foo bar")
but cout << "foo bar"
doesn't works
If you're using SwiftUI
If you're updating from a previous version of Xcode 11, there are some changes to the SceneDelegate
willConnectTo session: options connectionOptions
initialization:
The main window
is now initialized using UIWindow(windowScene: windowScene)
, where it use to be UIWindow(frame: UIScreen.main.bounds)
On previous version:
let window = UIWindow(frame: UIScreen.main.bounds)
window.rootViewController = UIHostingController(rootView: ContentView())
self.window = window
window.makeKeyAndVisible()
In new version:
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: ContentView())
self.window = window
window.makeKeyAndVisible()
}
You have the wrong URL.
I don't know what you mean by "JDBC 2005". When I looked on the microsoft site, I found something called the Microsoft SQL Server JDBC Driver 2.0. You're going to want that one - it includes lots of fixes and some perf improvements. [edit: you're probably going to want the latest driver. As of March 2012, the latest JDBC driver from Microsoft is JDBC 4.0]
Check the release notes. For this driver, you want:
URL: jdbc:sqlserver://server:port;DatabaseName=dbname
Class name: com.microsoft.sqlserver.jdbc.SQLServerDriver
It seems you have the class name correct, but the URL wrong.
Microsoft changed the class name and the URL after its initial release of a JDBC driver. The URL you are using goes with the original JDBC driver from Microsoft, the one MS calls the "SQL Server 2000 version". But that driver uses a different classname.
For all subsequent drivers, the URL changed to the form I have here.
This is in the release notes for the JDBC driver.
It's in the python docs.
import datetime
datetime.datetime.combine(datetime.date(2011, 1, 1),
datetime.time(10, 23))
returns
datetime.datetime(2011, 1, 1, 10, 23)
I ran into the same issue. What I needed to do was add a reference at the top of the class and change the CultureInfo of the thread that is currently executing.
using System.Threading;
string cultureName = "fr-CA";
Thread.CurrentThread.CurrentCulture = new CultureInfo(cultureName);
DateTime theDate = new DateTime(2015, 11, 06);
theDate.ToString("g");
Console.WriteLine(theDate);
All you have to do is change the culture name, for example: "en-US" = United States "fr-FR" = French-speaking France "fr-CA" = French-speaking Canada etc...
You could also use vbCrLf
which corresponds to Chr(13)
& Chr(10)
.
Microsoft says the SQL Server 2005 it's not compatible with Windows 8, but I've run it without problems (only using SP3) except the installation.
After you run the install file SQLExpr.exe
look for a hidden folder recently created in the C drive. Copy the contents to another folder and cancel the installer (or use WinRar to open the file and extract the contents to a temp folder)
After that, find the file sqlncli_x64.msi
in the setup folder, and run it.
Now you are ready the run the setup.exe
file and install SQL server 2005 without errors
Promo graphic
The promo graphic is used for promotions on older versions of the Android OS (earlier than 4.0). This image is not required to submit an update for your Store Listing.
Requirements
- JPG or 24-bit PNG (no alpha)
- Dimensions: 180px by 120px
https://support.google.com/googleplay/android-developer/answer/1078870
The command in DougWare's answer did not work, but this did:
reg delete "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v FOOBAR /f
The shortcut HKLM
can be used for HKEY_LOCAL_MACHINE
.
I did this.
class Circle
{
constuctor(radius)
{
this.radius = radius;
}
static get PI()
{
return 3.14159;
}
}
The value of PI is protected from being changed since it is a value being returned from a function. You can access it via Circle.PI. Any attempt to assign to it is simply dropped on the floor in a manner similar to an attempt to assign to a string character via [].
What you really want here is:
<col align="right"/>
but it looks like Gecko doesn't support this yet: it's been an open bug for over a decade.
(Geez, why can't Firefox have decent standards support like IE6?)
This should work:
$(".hit").click(function(){
var value=$(this).closest('tr').children('td:first').text();
alert(value);
});
Explanation:
.closest('tr')
gets the nearest ancestor that is a <tr>
element (so in this case the row where the <a>
element is in)..children('td:first')
gets all the children of this element, but with the :first
selector we reduce it to the first <td>
element..text()
gets the text inside the elementAs you can see from the other answers, there is more than only one way to do this.
apply()
was added in 2.3, it commits without returning a boolean indicating success or failure.
commit()
returns true if the save works, false otherwise.
apply()
was added as the Android dev team noticed that almost no one took notice of the return value, so apply is faster as it is asynchronous.
http://developer.android.com/reference/android/content/SharedPreferences.Editor.html#apply()
With something like this:
String mDrawableName = "myappicon";
int resID = getResources().getIdentifier(mDrawableName , "drawable", getPackageName());
You can do this by using /parent::node() in the xpath. Simply append /parent::node() to the child elements xpath.
For example: Let xpath of child element is childElementXpath.
Then xpath of its immediate ancestor would be childElementXpath/parent::node().
Xpath of its next ancestor would be childElementXpath/parent::node()/parent::node()
and so on..
Also, you can navigate to an ancestor of an element using
'childElementXpath/ancestor::*[@attr="attr_value"]'
. This would be useful when you have a known child element which is unique but has a parent element which cannot be uniquely identified.
Use red
, green
, blue
to convert to RGBA:
background-color: rgba(red($color), green($color), blue($color), 0.2);
You likely forgot to #include <stdlib.h>
Several of the examples here create a new Random
instance, but this is unnecessary. There is also no reason to use synchronized
as one solution does. Instead, take advantage of the methods on the ThreadLocalRandom
class:
double randomGenerator() {
return ThreadLocalRandom.current().nextDouble(0.5);
}
This is not an answer to the question but as I found this page while looking to an answer to a problem that I had, I want to mention the solution that I found as it cost me a lot of time. In the hope this will be useful to others:
The problem was that text in a <p> tag would not fold in the div. Eventually, I opened the inspector and noticed a 'no breaking space entity' between all the words. My editor, vi, was just showing normal blank spaces (some invisible chr, I don't know what) but I had copied pasted the text from a PDF document. The solution was to copy a blank space from within vi and replace it with a blank space. ie. :%s/ / /g where the blank to be replaced was copied from the offending text. Problem solved.
Unfortunately my reputation is to low to command underneath @Sujoy answer.
In their docs they claim to support python 3.6. The link provided by @mayur shows that their is indeed only a python3.5 wheel package. This is my try to install tensorflow:
Microsoft Windows [Version 10.0.16299.371]
(c) 2017 Microsoft Corporation. All rights reserved.
C:\>python3 -m pip install --upgrade pip
Requirement already up-to-date: pip in d:\python\v3\lib\site-packages (10.0.0)
C:\>python3 -m pip -V
pip 10.0.0 from D:\Python\V3\lib\site-packages\pip (python 3.6)
C:\>python3 -m pip install --upgrade tensorflow
Collecting tensorflow
Could not find a version that satisfies the requirement tensorflow (from versions: )
No matching distribution found for tensorflow
while python 3.5 seems to install successfully. I would love to see a python3.6 version since they claim it should also work on python3.6.
Quoted :
"TensorFlow supports Python 3.5.x and 3.6.x on Windows. Note that Python 3 comes with the pip3 package manager, which is the program you'll use to install TensorFlow."
Source : https://www.tensorflow.org/install/install_windows
Python3.5 install :
Microsoft Windows [Version 10.0.16299.371]
(c) 2017 Microsoft Corporation. All rights reserved.
C:\>python3 -m pip install --upgrade pip
Requirement already up-to-date: pip in d:\python\v3\lib\site-packages (10.0.0)
C:\>python3 -m pip -V
pip 10.0.0 from D:\Python\V3_5\lib\site-packages\pip (python 3.5.2)
C:\>python3 -m pip install --upgrade tensorflow
Collecting tensorflow
Downloading
....
....
I hope i am terrible wrong here but if not ring a alarm bell
Edit: A couple of posts below someone pointed out that the following command would work and it did.
python3 -m pip install --upgrade https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-0.12.0-py3-none-any.whl
Strange pip is not working
SP is the stack register a shortcut for typing r13. LR is the link register a shortcut for r14. And PC is the program counter a shortcut for typing r15.
When you perform a call, called a branch link instruction, bl, the return address is placed in r14, the link register. the program counter pc is changed to the address you are branching to.
There are a few stack pointers in the traditional ARM cores (the cortex-m series being an exception) when you hit an interrupt for example you are using a different stack than when running in the foreground, you dont have to change your code just use sp or r13 as normal the hardware has done the switch for you and uses the correct one when it decodes the instructions.
The traditional ARM instruction set (not thumb) gives you the freedom to use the stack in a grows up from lower addresses to higher addresses or grows down from high address to low addresses. the compilers and most folks set the stack pointer high and have it grow down from high addresses to lower addresses. For example maybe you have ram from 0x20000000 to 0x20008000 you set your linker script to build your program to run/use 0x20000000 and set your stack pointer to 0x20008000 in your startup code, at least the system/user stack pointer, you have to divide up the memory for other stacks if you need/use them.
Stack is just memory. Processors normally have special memory read/write instructions that are PC based and some that are stack based. The stack ones at a minimum are usually named push and pop but dont have to be (as with the traditional arm instructions).
If you go to http://github.com/lsasim I created a teaching processor and have an assembly language tutorial. Somewhere in there I go through a discussion about stacks. It is NOT an arm processor but the story is the same it should translate directly to what you are trying to understand on the arm or most other processors.
Say for example you have 20 variables you need in your program but only 16 registers minus at least three of them (sp, lr, pc) that are special purpose. You are going to have to keep some of your variables in ram. Lets say that r5 holds a variable that you use often enough that you dont want to keep it in ram, but there is one section of code where you really need another register to do something and r5 is not being used, you can save r5 on the stack with minimal effort while you reuse r5 for something else, then later, easily, restore it.
Traditional (well not all the way back to the beginning) arm syntax:
...
stmdb r13!,{r5}
...temporarily use r5 for something else...
ldmia r13!,{r5}
...
stm is store multiple you can save more than one register at a time, up to all of them in one instruction.
db means decrement before, this is a downward moving stack from high addresses to lower addresses.
You can use r13 or sp here to indicate the stack pointer. This particular instruction is not limited to stack operations, can be used for other things.
The ! means update the r13 register with the new address after it completes, here again stm can be used for non-stack operations so you might not want to change the base address register, leave the ! off in that case.
Then in the brackets { } list the registers you want to save, comma separated.
ldmia is the reverse, ldm means load multiple. ia means increment after and the rest is the same as stm
So if your stack pointer were at 0x20008000 when you hit the stmdb instruction seeing as there is one 32 bit register in the list it will decrement before it uses it the value in r13 so 0x20007FFC then it writes r5 to 0x20007FFC in memory and saves the value 0x20007FFC in r13. Later, assuming you have no bugs when you get to the ldmia instruction r13 has 0x20007FFC in it there is a single register in the list r5. So it reads memory at 0x20007FFC puts that value in r5, ia means increment after so 0x20007FFC increments one register size to 0x20008000 and the ! means write that number to r13 to complete the instruction.
Why would you use the stack instead of just a fixed memory location? Well the beauty of the above is that r13 can be anywhere it could be 0x20007654 when you run that code or 0x20002000 or whatever and the code still functions, even better if you use that code in a loop or with recursion it works and for each level of recursion you go you save a new copy of r5, you might have 30 saved copies depending on where you are in that loop. and as it unrolls it puts all the copies back as desired. with a single fixed memory location that doesnt work. This translates directly to C code as an example:
void myfun ( void )
{
int somedata;
}
In a C program like that the variable somedata lives on the stack, if you called myfun recursively you would have multiple copies of the value for somedata depending on how deep in the recursion. Also since that variable is only used within the function and is not needed elsewhere then you perhaps dont want to burn an amount of system memory for that variable for the life of the program you only want those bytes when in that function and free that memory when not in that function. that is what a stack is used for.
A global variable would not be found on the stack.
Going back...
Say you wanted to implement and call that function you would have some code/function you are in when you call the myfun function. The myfun function wants to use r5 and r6 when it is operating on something but it doesnt want to trash whatever someone called it was using r5 and r6 for so for the duration of myfun() you would want to save those registers on the stack. Likewise if you look into the branch link instruction (bl) and the link register lr (r14) there is only one link register, if you call a function from a function you will need to save the link register on each call otherwise you cant return.
...
bl myfun
<--- the return from my fun returns here
...
myfun:
stmdb sp!,{r5,r6,lr}
sub sp,#4 <--- make room for the somedata variable
...
some code here that uses r5 and r6
bl more_fun <-- this modifies lr, if we didnt save lr we wouldnt be able to return from myfun
<---- more_fun() returns here
...
add sp,#4 <-- take back the stack memory we allocated for the somedata variable
ldmia sp!,{r5,r6,lr}
mov pc,lr <---- return to whomever called myfun.
So hopefully you can see both the stack usage and link register. Other processors do the same kinds of things in a different way. for example some will put the return value on the stack and when you execute the return function it knows where to return to by pulling a value off of the stack. Compilers C/C++, etc will normally have a "calling convention" or application interface (ABI and EABI are names for the ones ARM has defined). if every function follows the calling convention, puts parameters it is passing to functions being called in the right registers or on the stack per the convention. And each function follows the rules as to what registers it does not have to preserve the contents of and what registers it has to preserve the contents of then you can have functions call functions call functions and do recursion and all kinds of things, so long as the stack does not go so deep that it runs into the memory used for globals and the heap and such, you can call functions and return from them all day long. The above implementation of myfun is very similar to what you would see a compiler produce.
ARM has many cores now and a few instruction sets the cortex-m series works a little differently as far as not having a bunch of modes and different stack pointers. And when executing thumb instructions in thumb mode you use the push and pop instructions which do not give you the freedom to use any register like stm it only uses r13 (sp) and you cannot save all the registers only a specific subset of them. the popular arm assemblers allow you to use
push {r5,r6}
...
pop {r5,r6}
in arm code as well as thumb code. For the arm code it encodes the proper stmdb and ldmia. (in thumb mode you also dont have the choice as to when and where you use db, decrement before, and ia, increment after).
No you absolutly do not have to use the same registers and you dont have to pair up the same number of registers.
push {r5,r6,r7}
...
pop {r2,r3}
...
pop {r1}
assuming there is no other stack pointer modifications in between those instructions if you remember the sp is going to be decremented 12 bytes for the push lets say from 0x1000 to 0x0FF4, r5 will be written to 0xFF4, r6 to 0xFF8 and r7 to 0xFFC the stack pointer will change to 0x0FF4. the first pop will take the value at 0x0FF4 and put that in r2 then the value at 0x0FF8 and put that in r3 the stack pointer gets the value 0x0FFC. later the last pop, the sp is 0x0FFC that is read and the value placed in r1, the stack pointer then gets the value 0x1000, where it started.
The ARM ARM, ARM Architectural Reference Manual (infocenter.arm.com, reference manuals, find the one for ARMv5 and download it, this is the traditional ARM ARM with ARM and thumb instructions) contains pseudo code for the ldm and stm ARM istructions for the complete picture as to how these are used. Likewise well the whole book is about the arm and how to program it. Up front the programmers model chapter walks you through all of the registers in all of the modes, etc.
If you are programming an ARM processor you should start by determining (the chip vendor should tell you, ARM does not make chips it makes cores that chip vendors put in their chips) exactly which core you have. Then go to the arm website and find the ARM ARM for that family and find the TRM (technical reference manual) for the specific core including revision if the vendor has supplied that (r2p0 means revision 2.0 (two point zero, 2p0)), even if there is a newer rev, use the manual that goes with the one the vendor used in their design. Not every core supports every instruction or mode the TRM tells you the modes and instructions supported the ARM ARM throws a blanket over the features for the whole family of processors that that core lives in. Note that the ARM7TDMI is an ARMv4 NOT an ARMv7 likewise the ARM9 is not an ARMv9. ARMvNUMBER is the family name ARM7, ARM11 without a v is the core name. The newer cores have names like Cortex and mpcore instead of the ARMNUMBER thing, which reduces confusion. Of course they had to add the confusion back by making an ARMv7-m (cortex-MNUMBER) and the ARMv7-a (Cortex-ANUMBER) which are very different families, one is for heavy loads, desktops, laptops, etc the other is for microcontrollers, clocks and blinking lights on a coffee maker and things like that. google beagleboard (Cortex-A) and the stm32 value line discovery board (Cortex-M) to get a feel for the differences. Or even the open-rd.org board which uses multiple cores at more than a gigahertz or the newer tegra 2 from nvidia, same deal super scaler, muti core, multi gigahertz. A cortex-m barely brakes the 100MHz barrier and has memory measured in kbytes although it probably runs of a battery for months if you wanted it to where a cortex-a not so much.
sorry for the very long post, hope it is useful.
Following document published by W3C also describes the differences between SOAP 1.1 and 1.2:
Inline elements:
Block elements:
Inline-block elements:
From W3Schools:
An inline element has no line break before or after it, and it tolerates HTML elements next to it.
A block element has some whitespace above and below it and does not tolerate any HTML elements next to it.
An inline-block element is placed as an inline element (on the same line as adjacent content), but it behaves as a block element.
When you visualize this, it looks like this:
The image is taken from this page, which also talks some more about this subject.
Try something like:
WHERE (column LIKE '%this%' OR column LIKE '%that%') AND something = else
For angular 4+ versions you can try
<input [readonly]="true" type="date" name="date" />
string replaceinString(std::string str, std::string tofind, std::string toreplace)
{
size_t position = 0;
for ( position = str.find(tofind); position != std::string::npos; position = str.find(tofind,position) )
{
str.replace(position ,1, toreplace);
}
return(str);
}
use it:
string replace = replaceinString(thisstring, " ", "%20");
string replace2 = replaceinString(thisstring, " ", "-");
string replace3 = replaceinString(thisstring, " ", "+");
You must specify the full path of the resource file as the name of 'image within the resources of your application, see example below.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
PictureBox1.Image = My.Resources.Chrysanthemum
End Sub
In the path assigned to the Image property after MyResources specify the name of the resource.
But before you do whatever you have to import in the resource section of your application from an image file exists or it can create your own.
Bye
try this it worked for me in ie 7 and ie 8
$(this).click(function (j) {
var href = ($(this).attr('href'));
window.location = href;
return true;
On PyCharm Community or Professional Edition 2019.1+ :
file2.txt file3.txt
, or --myFlag myArg --anotherFlag mySecondArg
)You cannot SELECT .. INTO .. a TABLE VARIABLE. The best you can do is create it first, then insert into it. Your 2nd snippet has to be
DECLARE @TempCustomer TABLE
(
CustomerId uniqueidentifier,
FirstName nvarchar(100),
LastName nvarchar(100),
Email nvarchar(100)
);
INSERT INTO
@TempCustomer
SELECT
CustomerId,
FirstName,
LastName,
Email
FROM
Customer
WHERE
CustomerId = @CustomerId
If already tried all of above solution but still hit error. Try to configure your genymotion same with me:
Old question, I know. Disabling the cache facility is not needed and not the best way to manage the problem. By disabling the cache facility the server needs to work harder and generates more traffic. Also the browser and device needs to work harder, especially on mobile devices this could be a problem.
The empty page can be easily solved by using Shift key+reload button at the browser.
The empty page can be a result of:
Try first the Shift keyboard key + reload button and see if the problem still exists and review your code.
You can filter out the columns you DO want using 'filter'
import pandas as pd
import numpy as np
data2 = [{'test2': 1, 'result1': 2}, {'test': 5, 'result34': 10, 'c': 20}]
df = pd.DataFrame(data2)
df
c result1 result34 test test2
0 NaN 2.0 NaN NaN 1.0
1 20.0 NaN 10.0 5.0 NaN
Now filter
df.filter(like='result',axis=1)
Get..
result1 result34
0 2.0 NaN
1 NaN 10.0
In following 97 ascii value of small "a".
public static char randomSeriesForThreeCharacter() {
Random r = new Random();
char random_3_Char = (char) (97 + r.nextInt(3));
return random_3_Char;
}
in above 3 number for a , b , c or d and if u want all character like a to z then you replace 3 number to 25.
I would use REGEX with .replace
like this:
window.location.href = window.location.href.replace( /[\?#].*|$/, "?single" );
If you want to change the bar/line color and the hint text color of the TextInputLayout
(what the accent color normally is), then just create this style:
<style name="MyStyle">
<item name="colorAccent">@color/your_color</item>
</style>
Then apply it to your TextInputLayout
as a theme:
<android.support.design.widget.TextInputLayout
...
app:theme="@style/MyStyle" />
This basically sets a theme (not style) to one view (as opposed to the whole activity).
To update Angular CLI to a new version, you must update both the global package and your project's local package.
Global package:
npm uninstall -g @angular/cli
npm cache clean
npm install -g @angular/cli@latest
Local project package:
rm -rf node_modules dist # use rmdir /S/Q node_modules dist in Windows Command Prompt; use rm -r -fo node_modules,dist in Windows PowerShell
npm install --save-dev @angular/cli@latest
npm install
See the reference https://github.com/angular/angular-cli
If your viewport gets scrolled after the dialog displays, it will no longer be centered. It's possible to unintentionally cause the viewport to scroll by adding/removing content from the page. You can recenter the dialog window during scroll/resize events by calling:
$('my-selector').dialog('option', 'position', 'center');
I recently had to build something similar. You can check it out in the snippet below.
The version I had to build uses the same button to start and stop the spinner, but you can manipulate to code if you have a button to start the spin and a different button to stop the spin
Basically, my code looks like this...
Run Code Snippet
var rocket = document.querySelector('.rocket');_x000D_
var btn = document.querySelector('.toggle');_x000D_
var rotate = false;_x000D_
var runner;_x000D_
var degrees = 0;_x000D_
_x000D_
function start(){_x000D_
runner = setInterval(function(){_x000D_
degrees++;_x000D_
rocket.style.webkitTransform = 'rotate(' + degrees + 'deg)';_x000D_
},50)_x000D_
}_x000D_
_x000D_
function stop(){_x000D_
clearInterval(runner);_x000D_
}_x000D_
_x000D_
btn.addEventListener('click', function(){_x000D_
if (!rotate){_x000D_
rotate = true;_x000D_
start();_x000D_
} else {_x000D_
rotate = false;_x000D_
stop();_x000D_
}_x000D_
})
_x000D_
body {_x000D_
background: #1e1e1e;_x000D_
} _x000D_
_x000D_
.rocket {_x000D_
width: 150px;_x000D_
height: 150px;_x000D_
margin: 1em;_x000D_
border: 3px dashed teal;_x000D_
border-radius: 50%;_x000D_
background-color: rgba(128,128,128,0.5);_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
align-items: center;_x000D_
}_x000D_
_x000D_
.rocket h1 {_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
font-size: .8em;_x000D_
color: skyblue;_x000D_
letter-spacing: 1em;_x000D_
text-shadow: 0 0 10px black;_x000D_
}_x000D_
_x000D_
.toggle {_x000D_
margin: 10px;_x000D_
background: #000;_x000D_
color: white;_x000D_
font-size: 1em;_x000D_
padding: .3em;_x000D_
border: 2px solid red;_x000D_
outline: none;_x000D_
letter-spacing: 3px;_x000D_
}
_x000D_
<div class="rocket"><h1>SPIN ME</h1></div>_x000D_
<button class="toggle">I/0</button>
_x000D_
None of the answers here quite hit the nail on the head.
How to store a datetime in MySQL with timezone info
Use two columns: DATETIME
, and a VARCHAR
to hold the time zone information, which may be in several forms:
A timezone or location such as America/New_York
is the highest data fidelity.
A timezone abbreviation such as PST
is the next highest fidelity.
A time offset such as -2:00
is the smallest amount of data in this regard.
Some key points:
TIMESTAMP
because it's limited to the year 2038, and MySQL relates it to the server timezone, which is probably undesired.INT
field, because there are half-hour and quarter-hour offsets.If it's important for your use case to have MySQL compare or sort these dates chronologically, DATETIME
has a problem:
'2009-11-10 11:00:00 -0500'
is before '2009-11-10 10:00:00 -0700'
in terms of "instant in time", but they would sort the other way when inserted into a DATETIME
.
You can do your own conversion to UTC. In the above example, you would then have '2009-11-10 16:00:00'
and '2009-11-10 17:00:00'
respectively, which would sort correctly. When retrieving the data, you would then use the timezone info to revert it to its original form.
One recommendation which I quite like is to have three columns:
local_time DATETIME
utc_time DATETIME
time_zone VARCHAR(X)
where X is appropriate for what kind of data you're storing there. (I would choose 64 characters for timezone/location.)An advantage to the 3-column approach is that it's explicit: with a single DATETIME
column, you can't tell at a glance if it's been converted to UTC before insertion.
Regarding the descent of accuracy through timezone/abbreviation/offset:
America/Juneau
, you can know accurately what the wall clock time is for them at any point in the past or future (barring changes to the way Daylight Savings is handled in that location). The start/end points of DST, and whether it's used at all, are dependent upon location, so this is the only reliable way.-0700
, you will be unable to predict a wall clock time in the past or future. For example, in the United States, Colorado and Arizona both use MST, but Arizona doesn't observe DST. So if the user uploads his cat photo at 14:00 -0700
during the winter months, was he in Arizona or California? If you added six months exactly to that date, would it be 14:00
or 13:00
for the user?These things are important to consider when your application has time, dates, or scheduling as core function.
References:
Assuming you don't want to make it a block element, then you might try:
.title {
display: inline-block; /* which allows you to set the height/width; but this isn't cross-browser, particularly as regards IE < 7 */
line-height: 2em; /* or */
padding-top: 1em;
padding-bottom: 1em;
}
But the easiest solution is to simply treat the .title
as a block-level element, and using the appropriate heading tags <h1>
through <h6>
.
I have seen errors on standard functions if there was a reference to a totally different library missing.
In the VBA editor launch the Compile command from the menu and then check the References dialog to see if there is anything missing and if so try to add these libraries.
In general it seems to be good practice to compile the complete VBA code and then saving the document before distribution.
Based on posted answered, this worked for me:
/* check for iOS 6 or 7 */
if ([[self navigationController].navigationBar respondsToSelector:@selector(setBarTintColor:)]) {
[[self navigationController].navigationBar setBarTintColor:[UIColor whiteColor]];
} else {
/* Set background and foreground */
[[self navigationController].navigationBar setTintColor:[UIColor whiteColor]];
[self navigationController].navigationBar.titleTextAttributes = [[NSDictionary alloc] initWithObjectsAndKeys:[UIColor blackColor],UITextAttributeTextColor,nil];
}
With RxJS
:
import { timer } from 'rxjs';
// ...
timer(your_delay_in_ms).subscribe(x => { your_action_code_here })
x
is 0.
If you give a second argument period
to timer
, a new number will be emitted each period
milliseconds (x = 0 then x = 1, x = 2, ...).
See the official doc for more details.
You could also create an ssh tunnel.
docker-compose.yml
:
---
version: '2'
services:
kibana:
image: "kibana:4.5.1"
links:
- elasticsearch
volumes:
- ./config/kibana:/opt/kibana/config:ro
elasticsearch:
build:
context: .
dockerfile: ./docker/Dockerfile.tunnel
entrypoint: ssh
command: "-N elasticsearch -L 0.0.0.0:9200:localhost:9200"
docker/Dockerfile.tunnel
:
FROM buildpack-deps:jessie
RUN apt-get update && \
DEBIAN_FRONTEND=noninteractive \
apt-get -y install ssh && \
apt-get clean && \
rm -rf /var/lib/apt/lists/*
COPY ./config/ssh/id_rsa /root/.ssh/id_rsa
COPY ./config/ssh/config /root/.ssh/config
COPY ./config/ssh/known_hosts /root/.ssh/known_hosts
RUN chmod 600 /root/.ssh/id_rsa && \
chmod 600 /root/.ssh/config && \
chown $USER:$USER -R /root/.ssh
config/ssh/config
:
# Elasticsearch Server
Host elasticsearch
HostName jump.host.czerasz.com
User czerasz
ForwardAgent yes
IdentityFile ~/.ssh/id_rsa
This way the elasticsearch
has a tunnel to the server with the running service (Elasticsearch, MongoDB, PostgreSQL) and exposes port 9200 with that service.
You can use fit-content
value for width
.
#wrap {
width: -moz-fit-content;
width: -webkit-fit-content;
width: fit-content;
margin: auto;
}
Note: It works only in latest browsers.
Nobody seems to implemented an extension method. With the help of @CMS's answer:
Working and improved full source example is here: Gist Link
namespace ExtensionMethods {
using System;
using System.Globalization;
public static class DateTimeExtensions {
public static DateTime ToDateTime(this string s,
string format = "ddMMyyyy", string cultureString = "tr-TR") {
try {
var r = DateTime.ParseExact(
s: s,
format: format,
provider: CultureInfo.GetCultureInfo(cultureString));
return r;
} catch (FormatException) {
throw;
} catch (CultureNotFoundException) {
throw; // Given Culture is not supported culture
}
}
public static DateTime ToDateTime(this string s,
string format, CultureInfo culture) {
try {
var r = DateTime.ParseExact(s: s, format: format,
provider: culture);
return r;
} catch (FormatException) {
throw;
} catch (CultureNotFoundException) {
throw; // Given Culture is not supported culture
}
}
}
}
namespace SO {
using ExtensionMethods;
using System;
using System.Globalization;
class Program {
static void Main(string[] args) {
var mydate = "29021996";
var date = mydate.ToDateTime(format: "ddMMyyyy"); // {29.02.1996 00:00:00}
mydate = "2016 3";
date = mydate.ToDateTime("yyyy M"); // {01.03.2016 00:00:00}
mydate = "2016 12";
date = mydate.ToDateTime("yyyy d"); // {12.01.2016 00:00:00}
mydate = "2016/31/05 13:33";
date = mydate.ToDateTime("yyyy/d/M HH:mm"); // {31.05.2016 13:33:00}
mydate = "2016/31 Ocak";
date = mydate.ToDateTime("yyyy/d MMMM"); // {31.01.2016 00:00:00}
mydate = "2016/31 January";
date = mydate.ToDateTime("yyyy/d MMMM", cultureString: "en-US");
// {31.01.2016 00:00:00}
mydate = "11/?????/1437";
date = mydate.ToDateTime(
culture: CultureInfo.GetCultureInfo("ar-SA"),
format: "dd/MMMM/yyyy");
// Weird :) I supposed dd/yyyy/MMMM but that did not work !?$^&*
System.Diagnostics.Debug.Assert(
date.Equals(new DateTime(year: 2016, month: 5, day: 18)));
}
}
}
You can use the 'expect' script on unix/terminal
For example create 'test.exp' :
#!/usr/bin/expect
spawn scp /usr/bin/file.txt root@<ServerLocation>:/home
set pass "Your_Password"
expect {
password: {send "$pass\r"; exp_continue}
}
run the script
expect test.exp
I hope that helps.
Try using this tool,which is just a simple js script https://github.com/shashwatsahai/CSSExtractor/ This tool helps in getting the CSS from a specific page listing all sources for active styles and save it to a JSON with source as key and rules as value. It loads all the CSS from the href links and tells all the styles applied from them You can modify the code to save all css into a .css file. Thereby combining all your css.
You can solve the issue by clearing value of address in endpoint tag in web.config:
<endpoint address="" name="wsHttpEndpoint" ....... />
You can use ROW_NUMBER()
function to get what you want:
SELECT *
FROM (SELECT ROW_NUMBER() OVER(ORDER BY id) RowNr, id FROM tbl) t
WHERE RowNr BETWEEN 10 AND 20
SQL*Plus uses &1, &2... &n to access the parameters.
Suppose you have the following script test.sql
:
SET SERVEROUTPUT ON
SPOOL test.log
EXEC dbms_output.put_line('&1 &2');
SPOOL off
you could call this script like this for example:
$ sqlplus login/pw @test Hello World!
In a UNIX script you would usually call a SQL script like this:
sqlplus /nolog << EOF
connect user/password@db
@test.sql Hello World!
exit
EOF
so that your login/password won't be visible with another session's ps
Change directory to tomcat/bin directory in cmd prompt
cd C:\Program Files\Apache Software Foundation\Tomcat 8.0\bin
Run the below command to start:
On Linux: >startup.sh
On Windows: >startup.bat
Run these commands to stop
On Linux: shutdown.sh
On Windows: shutdown.bat
If the return value is string and you need to search by Id you can use:
string name = datatable.AsEnumerable().Where(row => Convert.ToInt32(row["Id"]) == Id).Select(row => row.Field<string>("name")).ToString();
or using generic variable:
var name = datatable.AsEnumerable().Where(row => Convert.ToInt32(row["Id"]) == Id).Select(row => row.Field<string>("name"));
Ok, per pix0r's, Sparks' and Dave's answers it looks like there are three ways to do this:
NameVirtualHost *:80
).Add your virtual host (~line 36):
<VirtualHost *:80>
DocumentRoot C:\Projects\transitCalculator\trunk
ServerName transitcalculator.localhost
<Directory C:\Projects\transitCalculator\trunk>
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
Open your hosts file (C:\Windows\System32\drivers\etc\hosts).
Add
127.0.0.1 transitcalculator.localhost #transitCalculator
to the end of the file (before the Spybot - Search & Destroy stuff if you have that installed).
Now you can access that directory by browsing to http://transitcalculator.localhost/.
Starting ~line 200 of your http.conf
file, copy everything between <Directory "C:/xampp/htdocs">
and </Directory>
(~line 232) and paste it immediately below with C:/xampp/htdocs
replaced with your desired directory (in this case C:/Projects
) to give your server the correct permissions for the new directory.
Find the <IfModule alias_module></IfModule>
section (~line 300) and add
Alias /transitCalculator "C:/Projects/transitCalculator/trunk"
(or whatever is relevant to your desires) below the Alias
comment block, inside the module tags.
Edit ~line 176 in C:\xampp\apache\conf\httpd.conf; change DocumentRoot "C:/xampp/htdocs"
to #DocumentRoot "C:/Projects"
(or whatever you want).
Edit ~line 203 to match your new location (in this case C:/Projects
).
Notes:
By using iter
builtin:
l = [1, 2, 3]
# i is the first item.
i = iter(l)
next(i)
for d in i:
print(d)
toInteger()
method is available in groovy, you could use that.
As it's 2018, use flexbox - no more inline-block
whitespace issues:
body {
margin: 0;
}
#wrapper {
display: flex;
height: 200px;
}
#wrapper > div {
flex-grow: 1;
}
#wrapper > div:first-of-type { background-color: red }
#wrapper > div:nth-of-type(2) { background-color: blue }
#wrapper > div:nth-of-type(3) { background-color: green }
_x000D_
<div id="wrapper">
<div id="c1"></div>
<div id="c2"></div>
<div id="c3"></div>
</div>
_x000D_
Or even CSS grid if you are creating a grid.
body {
margin: 0;
}
#wrapper {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-auto-rows: minmax(200px, auto);
}
#wrapper>div:first-of-type { background-color: red }
#wrapper>div:nth-of-type(2) { background-color: blue }
#wrapper>div:nth-of-type(3) { background-color: green }
_x000D_
<div id="wrapper">
<div id="c1"></div>
<div id="c2"></div>
<div id="c3"></div>
</div>
_x000D_
Use CSS calc()
:
body {
margin: 0;
}
div {
height: 200px;
width: 33.33%; /* as @passatgt mentioned in the comment, for the older browsers fallback */
width: calc(100% / 3);
display: inline-block;
}
div:first-of-type { background-color: red }
div:nth-of-type(2) { background-color: blue }
div:nth-of-type(3) { background-color: green }
_x000D_
<div></div><div></div><div></div>
_x000D_
References:
I started my journey in the Python <-> C++ binding from this page, with the objective of linking high level data types (multidimensional STL vectors with Python lists) :-)
Having tried the solutions based on both ctypes and boost.python (and not being a software engineer) I have found them complex when high level datatypes binding is required, while I have found SWIG much more simple for such cases.
This example uses therefore SWIG, and it has been tested in Linux (but SWIG is available and is widely used in Windows too).
The objective is to make a C++ function available to Python that takes a matrix in form of a 2D STL vector and returns an average of each row (as a 1D STL vector).
The code in C++ ("code.cpp") is as follow:
#include <vector>
#include "code.h"
using namespace std;
vector<double> average (vector< vector<double> > i_matrix) {
// Compute average of each row..
vector <double> averages;
for (int r = 0; r < i_matrix.size(); r++){
double rsum = 0.0;
double ncols= i_matrix[r].size();
for (int c = 0; c< i_matrix[r].size(); c++){
rsum += i_matrix[r][c];
}
averages.push_back(rsum/ncols);
}
return averages;
}
The equivalent header ("code.h") is:
#ifndef _code
#define _code
#include <vector>
std::vector<double> average (std::vector< std::vector<double> > i_matrix);
#endif
We first compile the C++ code to create an object file:
g++ -c -fPIC code.cpp
We then define a SWIG interface definition file ("code.i") for our C++ functions.
%module code
%{
#include "code.h"
%}
%include "std_vector.i"
namespace std {
/* On a side note, the names VecDouble and VecVecdouble can be changed, but the order of first the inner vector matters! */
%template(VecDouble) vector<double>;
%template(VecVecdouble) vector< vector<double> >;
}
%include "code.h"
Using SWIG, we generate a C++ interface source code from the SWIG interface definition file..
swig -c++ -python code.i
We finally compile the generated C++ interface source file and link everything together to generate a shared library that is directly importable by Python (the "_" matters):
g++ -c -fPIC code_wrap.cxx -I/usr/include/python2.7 -I/usr/lib/python2.7
g++ -shared -Wl,-soname,_code.so -o _code.so code.o code_wrap.o
We can now use the function in Python scripts:
#!/usr/bin/env python
import code
a= [[3,5,7],[8,10,12]]
print a
b = code.average(a)
print "Assignment done"
print a
print b
It depends on what you are trying to do.
file, err := os.Open("file.txt")
fmt.print(file)
The reason it outputs &{0xc082016240}, is because you are printing the pointer value of a file-descriptor (*os.File
), not file-content. To obtain file-content, you may READ
from a file-descriptor.
To read all file content(in bytes) to memory, ioutil.ReadAll
package main
import (
"fmt"
"io/ioutil"
"os"
"log"
)
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
b, err := ioutil.ReadAll(file)
fmt.Print(b)
}
But sometimes, if the file size is big, it might be more memory-efficient to just read in chunks: buffer-size, hence you could use the implementation of io.Reader.Read
from *os.File
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
buf := make([]byte, 32*1024) // define your buffer size here.
for {
n, err := file.Read(buf)
if n > 0 {
fmt.Print(buf[:n]) // your read buffer.
}
if err == io.EOF {
break
}
if err != nil {
log.Printf("read %d bytes: %v", n, err)
break
}
}
}
Otherwise, you could also use the standard util package: bufio
, try Scanner
. A Scanner
reads your file in tokens: separator.
By default, scanner advances the token by newline (of course you can customise how scanner should tokenise your file, learn from here the bufio test).
package main
import (
"fmt"
"os"
"log"
"bufio"
)
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
scanner := bufio.NewScanner(file)
for scanner.Scan() { // internally, it advances token based on sperator
fmt.Println(scanner.Text()) // token in unicode-char
fmt.Println(scanner.Bytes()) // token in bytes
}
}
Lastly, I would also like to reference you to this awesome site: go-lang file cheatsheet. It encompassed pretty much everything related to working with files in go-lang, hope you'll find it useful.
Don't echo out HTML.
If you want to use
<?php echo "<h1> $title; </h1>"; ?>
you should be doing this:
<h1><?= $title;?></h1>
Could you use dynamic SQL to execute each statement in turn? You would probably have to write a PL/pgSQL script to do this.
http://www.postgresql.org/docs/8.3/static/plpgsql-statements.html (section 38.5.4. Executing Dynamic Commands)
this function should work. basically does a recursive lookup till we get a distinct list of leaf nodes.
function distinctNodes(search, element) {
var d, e, ef;
e = [];
ef = [];
if (element) {
d = $(":contains(\""+ search + "\"):not(script)", element);
}
else {
d = $(":contains(\""+ search + "\"):not(script)");
}
if (d.length == 1) {
e.push(d[0]);
}
else {
d.each(function () {
var i, r = distinctNodes(search, this);
if (r.length === 0) {
e.push(this);
}
else {
for (i = 0; i < r.length; ++i) {
e.push(r[i]);
}
}
});
}
$.each(e, function () {
for (var i = 0; i < ef.length; ++i) {
if (this === ef[i]) return;
}
ef.push(this);
});
return ef;
}
Sorting dictionaries by value using comprehensions. I think it's nice as 1 line and no need for functions or lambdas
a = {'b':'foo', 'c':'bar', 'e': 'baz'}
a = {f:a[f] for f in sorted(a, key=a.__getitem__)}
First of all you should not merge the Fluent Api with the data annotation so I would suggest you to use one of the below:
make sure you have correclty set the keys
modelBuilder.Entity<Foo>()
.HasKey(p => new { p.Name, p.Id });
modelBuilder.Entity<Foo>().Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
OR you can achieve it using data annotation as well
public class Foo
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key, Column(Order = 0)]
public int Id { get; set; }
[Key, Column(Order = 1)]
public string Name{ get; set; }
}
I think you want this:
select *
from dbo.table
where DATALENGTH(column_name) = 3
Just use date
and trusty seconds:
As you rightly point out, a lot of the details about the underlying computation are hidden if you rely on English time arithmetic. E.g. -d yesterday
, and -d 1 day ago
will have different behaviour.
Instead, you can reliably depend on the (precisely documented) seconds since the unix epoch UTC, and bash arithmetic to obtain the moment you want:
date -d @$(( $(date +"%s") - 24*3600)) +"%Y-%m-%d"
This was pointed out in another answer. This form is more portable across platforms with different date
command line flags, is language-independent (e.g. "yesterday" vs "hier" in French locale), and frankly (in the long-term) will be easier to remember, because well, you know it already. You might otherwise keep asking yourself: "Was it -d 2 hours ago
or -d 2 hour ago
again?" or "Is it -d yesterday
or -d 1 day ago
that I want?"). The only tricky bit here is the @
.
Armed with bash and nothing else:
Bash solely on bash, you can also get yesterday's time, via the printf builtin:
%(datefmt)T
causes printf to output the date-time string resulting from using
datefmt as a format string for strftime(3). The corresponding argu-
ment is an integer representing the number of seconds since the
epoch. Two special argument values may be used: -1 represents the
current time, and -2 represents the time the shell was invoked.
If no argument is specified, conversion behaves as if -1 had
been given.
This is an exception to the usual printf behavior.
So,
# inner printf gets you the current unix time in seconds
# outer printf spits it out according to the format
printf "%(%Y-%m-%d)T\n" $(( $(printf "%(%s)T" -1) - 24*3600 ))
or, equivalently with a temp variable (outer subshell optional, but keeps environment vars clean).
(
now=$(printf "%(%s)T" -1);
printf "%(%Y-%m-%d)T\n" $((now - 24*3600));
)
Note: despite the manpage stating that no argument to the %()T
formatter will assume a default -1
, i seem to get a 0 instead (thank you, bash manual version 4.3.48)
As you said GWT does not support reflection. You should use deferred binding instead of reflection, or third party library such as gwt-ent for reflection suppport at gwt layer.
Use System.currentTimeMillis() or System.nanoTime().
I got this on Firefox (FF58). I fixed this with:
dom.moduleScripts.enabled
in about:config
Source: Import page on mozilla (See Browser compatibility)
type="module"
to your script tag where you import the js file<script type="module" src="appthatimports.js"></script>
./
, /
, ../
or http://
before)import * from "./mylib.js"
For more examples, this blog post is good.
I agree that using jQuery is the best option. You should also avoid using body's onload function and use jQuery's ready function instead. As for the event listeners, they should be functions that take one argument:
document.getElementById("foo").onclick = function (event){alert('foo');};
or in jQuery:
$('#foo').click(function(event) { alert('foo'); }
You need to use overflow option like below:
.nav{
max-height: 300px;
overflow-y: scroll;
}
Change the height according to amount of items you need to show
This is what worked for me using Explicit Wait from here WebDriver: Advanced Usage
public void checkAlert() {
try {
WebDriverWait wait = new WebDriverWait(driver, 2);
wait.until(ExpectedConditions.alertIsPresent());
Alert alert = driver.switchTo().alert();
alert.accept();
} catch (Exception e) {
//exception handling
}
}
Why would you want to remove the linking, it makes it very user friendly to have th eoption.
If you simply want to remove the auto editing, but keep the link working just add this into your CSS...
a[href^=tel] {
color: inherit;
text-decoration:inherit;
}
Taken from this answer.
packages.config
file. This is the first time I see ignoring a problem actually makes it go away...
Edit in 2020: if you are viewing this warning, consider upgrading to PackageReference if you can
WITH (NOLOCK) is the equivalent of using READ UNCOMMITED as a transaction isolation level. So, you stand the risk of reading an uncommitted row that is subsequently rolled back, i.e. data that never made it into the database. So, while it can prevent reads being deadlocked by other operations, it comes with a risk. In a banking application with high transaction rates, it's probably not going to be the right solution to whatever problem you're trying to solve with it IMHO.
An HTTP message may have a body of data sent after the header lines. In a response, this is where the requested resource is returned to the client (the most common use of the message body), or perhaps explanatory text if there's an error. In a request, this is where user-entered data or uploaded files are sent to the server.
You have to use GROUP BY
so you will have multiple records returned,
SELECT COUNT(*) TotalCount,
b.category_id,
b.category_name
FROM table1 a
INNER JOIN table2 b
ON a.category_id = b.category_id
WHERE a.colour <> 'red'
GROUP BY b.category_id, b.category_name
You could also write your entire function as a jQuery extension, so you could do something along the lines of `$('#element').showHideOther();
(function($) {
$.extend($.fn, {
showHideOther: function() {
$.each(this, function() {
var Id = $(this).attr('id');
alert(Id);
...
return this;
});
}
});
})(jQuery);
Not that it answers your question... Just food for thought.
What about that?
HTML
<div class="chart" id="graph" data-percent="88"></div>
Javascript
var el = document.getElementById('graph'); // get canvas
var options = {
percent: el.getAttribute('data-percent') || 25,
size: el.getAttribute('data-size') || 220,
lineWidth: el.getAttribute('data-line') || 15,
rotate: el.getAttribute('data-rotate') || 0
}
var canvas = document.createElement('canvas');
var span = document.createElement('span');
span.textContent = options.percent + '%';
if (typeof(G_vmlCanvasManager) !== 'undefined') {
G_vmlCanvasManager.initElement(canvas);
}
var ctx = canvas.getContext('2d');
canvas.width = canvas.height = options.size;
el.appendChild(span);
el.appendChild(canvas);
ctx.translate(options.size / 2, options.size / 2); // change center
ctx.rotate((-1 / 2 + options.rotate / 180) * Math.PI); // rotate -90 deg
//imd = ctx.getImageData(0, 0, 240, 240);
var radius = (options.size - options.lineWidth) / 2;
var drawCircle = function(color, lineWidth, percent) {
percent = Math.min(Math.max(0, percent || 1), 1);
ctx.beginPath();
ctx.arc(0, 0, radius, 0, Math.PI * 2 * percent, false);
ctx.strokeStyle = color;
ctx.lineCap = 'round'; // butt, round or square
ctx.lineWidth = lineWidth
ctx.stroke();
};
drawCircle('#efefef', options.lineWidth, 100 / 100);
drawCircle('#555555', options.lineWidth, options.percent / 100);
and CSS
div {
position:relative;
margin:80px;
width:220px; height:220px;
}
canvas {
display: block;
position:absolute;
top:0;
left:0;
}
span {
color:#555;
display:block;
line-height:220px;
text-align:center;
width:220px;
font-family:sans-serif;
font-size:40px;
font-weight:100;
margin-left:5px;
}
http://jsfiddle.net/Aapn8/3410/
Basic code was taken from Simple PIE Chart http://rendro.github.io/easy-pie-chart/
For example, if you want an array of int
pointers it will be int* a[10]
. It means that variable a
is a collection of 10 int*
s.
EDIT
I guess this is what you want to do:
class Bar
{
};
class Foo
{
public:
//Takes number of bar elements in the pointer array
Foo(int size_in);
~Foo();
void add(Bar& bar);
private:
//Pointer to bar array
Bar** m_pBarArr;
//Current fee bar index
int m_index;
};
Foo::Foo(int size_in) : m_index(0)
{
//Allocate memory for the array of bar pointers
m_pBarArr = new Bar*[size_in];
}
Foo::~Foo()
{
//Notice delete[] and not delete
delete[] m_pBarArr;
m_pBarArr = NULL;
}
void Foo::add(Bar &bar)
{
//Store the pointer into the array.
//This is dangerous, you are assuming that bar object
//is valid even when you try to use it
m_pBarArr[m_index++] = &bar;
}
Make sure JAVA_HOME is set and the path in environment variables. The PATH should be able to find the keytools.exe
Open “Windows search” and search for "Environment Variables"
Under “System variables” click the “New…” button and enter JAVA_HOME as “Variable name” and the path to your Java JDK directory under “Variable value” it should be similar to this C:\Program Files\Java\jre1.8.0_231
This Solution utilizes part of what @Newred and @Radu Di?a said. But will work in less standard cases.
$(this).attr('style').split(';').filter(item => item.startsWith('background-color'))[0].split(":")[1].replace(/\s/g, '');
The issue both of them have is that neither check for a space between background-color: and the color.
All of these will match with the above code.
background-color: #ffffff
background-color: #fffff;
background-color:#fffff;
A new, attractive solution is to use patchwork
. The syntax is very simple:
library(ggplot2)
library(patchwork)
p1 <- ggplot(df1, aes(x = x, y = y, colour = group)) +
geom_point(position = position_jitter(w = 0.04, h = 0.02), size = 1.8)
p2 <- ggplot(df2, aes(x = x, y = y, colour = group)) +
geom_point(position = position_jitter(w = 0.04, h = 0.02), size = 1.8)
combined <- p1 + p2 & theme(legend.position = "bottom")
combined + plot_layout(guides = "collect")
Created on 2019-12-13 by the reprex package (v0.2.1)
lstResult.Clear();
foreach (ManagementObject drive in new ManagementObjectSearcher("select * from Win32_DiskDrive where InterfaceType='USB'").Get())
{
foreach (ManagementObject partition in new ManagementObjectSearcher("ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" + drive["DeviceID"] + "'} WHERE AssocClass = Win32_DiskDriveToDiskPartition").Get())
{
foreach (ManagementObject disk in new ManagementObjectSearcher("ASSOCIATORS OF {Win32_DiskPartition.DeviceID='" + partition["DeviceID"] + "'} WHERE AssocClass = Win32_LogicalDiskToPartition").Get())
{
foreach (var item in disk.Properties)
{
object value = disk.GetPropertyValue(item.Name);
}
string valor = disk["Name"].ToString();
lstResult.Add(valor);
}
}
}
}
From a tech perspective: Just model what Google does when you hit them with too many queries at once. That should put a halt to a lot of it.
From a legal perspective: It sounds like the data you're publishing is not proprietary. Meaning you're publishing names and stats and other information that cannot be copyrighted.
If this is the case, the scrapers are not violating copyright by redistributing your information about artist name etc. However, they may be violating copyright when they load your site into memory because your site contains elements that are copyrightable (like layout etc).
I recommend reading about Facebook v. Power.com and seeing the arguments Facebook used to stop screen scraping. There are many legal ways you can go about trying to stop someone from scraping your website. They can be far reaching and imaginative. Sometimes the courts buy the arguments. Sometimes they don't.
But, assuming you're publishing public domain information that's not copyrightable like names and basic stats... you should just let it go in the name of free speech and open data. That is, what the web's all about.
One way to do it would be like this:
param(
[Parameter(Position=0)][String]$Vlan,
[Parameter(ValueFromRemainingArguments=$true)][String[]]$Hosts
) ...
This would allow multiple hosts to be entered with spaces.
From v0.11+, ... use df.iloc
.
In [7]: df.iloc[:,0]
Out[7]:
0 1
1 2
2 3
3 4
Name: x, dtype: int64
Other words printf absent in python... I'm surprised! Best code is
def printf(format, *args):
sys.stdout.write(format % args)
Because of this form allows not to print \n. All others no. That's why print is bad operator. And also you need write args in special form. There is no disadvantages in function above. It's a standard usual form of printf function.
As a note of caution this answer provided by the user above me is correct.
SharedPreferences preferences = this.getActivity().getSharedPreferences("pref",0);
However, if you attempt to get anything in the fragment before onAttach is called getActivity() will return null.
Integer.toBinaryString()
is an in-built method and will do quite well.
You can add join type as well:
Criteria c2 = c.createCriteria("mother", "mother", CriteriaSpecification.LEFT_JOIN);
Criteria c3 = c2.createCriteria("kind", "kind", CriteriaSpecification.LEFT_JOIN);
This can be done with a sed one-liner:
sed '/^#/d'
This says, "find all lines that start with # and delete them, leaving everything else."
Declaration says "this thing exists somewhere":
int foo(); // function
extern int bar; // variable
struct T
{
static int baz; // static member variable
};
Definition says "this thing exists here; make memory for it":
int foo() {} // function
int bar; // variable
int T::baz; // static member variable
Initialisation is optional at the point of definition for objects, and says "here is the initial value for this thing":
int bar = 0; // variable
int T::baz = 42; // static member variable
Sometimes it's possible at the point of declaration instead:
struct T
{
static int baz = 42;
};
…but that's getting into more complex features.
Here is some good explaination. check out it.
http://www.mssqltips.com/tip.asp?tip=1360
CHECKPOINT;
GO
DBCC DROPCLEANBUFFERS;
GO
From the linked article:
If all of the performance testing is conducted in SQL Server the best approach may be to issue a CHECKPOINT and then issue the DBCC DROPCLEANBUFFERS command. Although the CHECKPOINT process is an automatic internal system process in SQL Server and occurs on a regular basis, it is important to issue this command to write all of the dirty pages for the current database to disk and clean the buffers. Then the DBCC DROPCLEANBUFFERS command can be executed to remove all buffers from the buffer pool.
Uninstall mysql service through command prompt using the following command.
sc delete mysql
restart XAMPP
I had a similar problem, I have the same repository I wanted to import twice. I renamed the existing project by right clicking on the project > refactor > rename then imported it again.
Here is what the JSF javadocs have to say about the commandButton
action
attribute:
MethodExpression representing the application action to invoke when this component is activated by the user. The expression must evaluate to a public method that takes no parameters, and returns an Object (the toString() of which is called to derive the logical outcome) which is passed to the NavigationHandler for this application.
It would be illuminating to me if anyone can explain what that has to do with any of the answers on this page. It seems pretty clear that action
refers to some page's filename and not a method.
Put your domain name here: https://www.ssllabs.com/ssltest/analyze.html You should be able to see if there are any issues with your ssl certificate chain. I am guessing that you have SSL chain issues. A short description of the problem is that there's actually a list of certificates on your server (and not only one) and these need to be in the correct order. If they are there but not in the correct order, the website will be fine on desktop browsers (an iOs as well I think), but android is more strict about the order of certificates, and will give an error if the order is incorrect. To fix this you just need to re-order the certificates.
Method Object JComboBox.getSelectedItem()
returns a value that is wrapped by Object
type so you have to cast it accordingly.
Syntax:
YourType varName = (YourType)comboBox.getSelectedItem();`
String value = comboBox.getSelectedItem().toString();
Yes oracle is :
select * from user_tables
That is if you only want objects owned by the logged in user/schema
otherwise you can use all_tables
or dba_tables
which includes system tables.
SOAP (communication protocol) for communication between applications. Uses HTTP (port 80) or SMTP ( port 25 or 2525 ), for message negotiation and transmission.
rekaszeru
I noticed that you commented in 2011 but i thought i should post this answer anyway, in case anyone needs to "replace the original string" and runs into this answer ..
Im using a EditText as an example
// GIVE TARGET TEXT BOX A NAME
EditText textbox = (EditText) findViewById(R.id.your_textboxID);
// STRING TO REPLACE
String oldText = "hello"
String newText = "Hi";
String textBoxText = textbox.getText().toString();
// REPLACE STRINGS WITH RETURNED STRINGS
String returnedString = textBoxText.replace( oldText, newText );
// USE RETURNED STRINGS TO REPLACE NEW STRING INSIDE TEXTBOX
textbox.setText(returnedString);
This is untested, but it's just an example of using the returned string to replace the original layouts string with setText() !
Obviously this example requires that you have a EditText with the ID set to your_textboxID
While Andriy's proposal will work well for INSERTs of a small number of records, full table scans will be done on the final join as both 'enumerated' and '@new_super' are not indexed, resulting in poor performance for large inserts.
This can be resolved by specifying a primary key on the @new_super table, as follows:
DECLARE @new_super TABLE (
row_num INT IDENTITY(1,1) PRIMARY KEY CLUSTERED,
super_id int
);
This will result in the SQL optimizer scanning through the 'enumerated' table but doing an indexed join on @new_super to get the new key.
A slight improvement of the above accepted answer, that I think is more pythonic (asking for forgiveness is better than asking for permission)
column_widths = []
for row in workSheet.iter_rows():
for i, cell in enumerate(row):
try:
column_widths[i] = max(column_widths[i], len(str(cell.value)))
except IndexError:
column_widths.append(len(str(cell.value)))
for i, column_width in enumerate(column_widths):
workSheet.column_dimensions[get_column_letter(i + 1)].width = column_width
Use this in your ubuntu/Macbook to get the ip address of your system. Your mobile and system should be in the same network
ip addr | grep inet
This will give you an ip address which looks like 192.168.168.46
. Use this in your smartphone.
Hope this helps.
All of the code above was really helpful, but none of it quite answered my own need: grep
all *.tar.gz
files in the current directory to find a pattern that is specified as an argument in a reusable script to output:
It's what I was really hoping that zgrep
could do for me and it just can't.
Here's my solution:
pattern=$1
for f in *.tar.gz; do
echo "$f:"
tar -xzf "$f" --to-command 'grep --label="`basename $TAR_FILENAME`" -Hin '"$pattern ; true";
done
You can also replace the tar
line with the following if you'd like to test that all variables are expanding properly with a basic echo
statement:
tar -xzf "$f" --to-command 'echo "f:`basename $TAR_FILENAME` s:'"$pattern\""
Let me explain what's going on. Hopefully, the for
loop and the echo
of the archive filename in question is obvious.
tar -xzf
: x
extract, z
filter through gzip, f
based on the following archive file...
"$f"
: The archive file provided by the for loop (such as what you'd get by doing an ls
) in double-quotes to allow the variable to expand and ensure that the script is not broken by any file names with spaces, etc.
--to-command
: Pass the output of the tar command to another command rather than actually extracting files to the filesystem. Everything after this specifies what the command is (grep
) and what arguments we're passing to that command.
Let's break that part down by itself, since it's the "secret sauce" here.
'grep --label="`basename $TAR_FILENAME`" -Hin '"$pattern ; true"
First, we use a single-quote to start this chunk so that the executed sub-command (basename $TAR_FILENAME
) is not immediately expanded/resolved. More on that in a moment.
grep
: The command to be run on the (not actually) extracted files
--label=
: The label to prepend the results, the value of which is enclosed in double-quotes because we do want to have the grep
command resolve the $TAR_FILENAME
environment variable passed in by the tar
command.
basename $TAR_FILENAME
: Runs as a command (surrounded by backticks) and removes directory path and outputs only the name of the file
-Hin
: H
Display filename (provided by the label), i
Case insensitive search, n
Display line number of match
Then we "end" the first part of the command string with a single quote and start up the next part with a double quote so that the $pattern
, passed in as the first argument, can be resolved.
Realizing which quotes I needed to use where was the part that tripped me up the longest. Hopefully, this all makes sense to you and helps someone else out. Also, I hope I can find this in a year when I need it again (and I've forgotten about the script I made for it already!)
And it's been a bit a couple of weeks since I wrote the above and it's still super useful... but it wasn't quite good enough as files have piled up and searching for things has gotten more messy. I needed a way to limit what I looked at by the date of the file (only looking at more recent files). So here's that code. Hopefully it's fairly self-explanatory.
if [ -z "$1" ]; then
echo "Look within all tar.gz files for a string pattern, optionally only in recent files"
echo "Usage: targrep <string to search for> [start date]"
fi
pattern=$1
startdatein=$2
startdate=$(date -d "$startdatein" +%s)
for f in *.tar.gz; do
filedate=$(date -r "$f" +%s)
if [[ -z "$startdatein" ]] || [[ $filedate -ge $startdate ]]; then
echo "$f:"
tar -xzf "$f" --to-command 'grep --label="`basename $TAR_FILENAME`" -Hin '"$pattern ; true"
fi
done
And I can't stop tweaking this thing. I added an argument to filter by the name of the output files in the tar file. Wildcards work, too.
Usage:
targrep.sh [-d <start date>] [-f <filename to include>] <string to search for>
Example:
targrep.sh -d "1/1/2019" -f "*vehicle_models.csv" ford
while getopts "d:f:" opt; do
case $opt in
d) startdatein=$OPTARG;;
f) targetfile=$OPTARG;;
esac
done
shift "$((OPTIND-1))" # Discard options and bring forward remaining arguments
pattern=$1
echo "Searching for: $pattern"
if [[ -n $targetfile ]]; then
echo "in filenames: $targetfile"
fi
startdate=$(date -d "$startdatein" +%s)
for f in *.tar.gz; do
filedate=$(date -r "$f" +%s)
if [[ -z "$startdatein" ]] || [[ $filedate -ge $startdate ]]; then
echo "$f:"
if [[ -z "$targetfile" ]]; then
tar -xzf "$f" --to-command 'grep --label="`basename $TAR_FILENAME`" -Hin '"$pattern ; true"
else
tar -xzf "$f" --no-anchored "$targetfile" --to-command 'grep --label="`basename $TAR_FILENAME`" -Hin '"$pattern ; true"
fi
fi
done
Maybe this helps
For me removing the .nuget folder located in C:\Users\YourNameHere fixed the problem.
if you want to connect with oracle database
once it get start means you can access oracle database now. if you want connect another user you can write conn username/password e.g. conn scott/tiger; it will show connected........
http://docs.jquery.com/Plugins/Validation/Methods/required
edit the code for 'select' as below for checking for a 0 or null value selection from select list
case 'select':
var options = $("option:selected", element);
return (options[0].value != 0 && options.length > 0 && options[0].value != '') && (element.type == "select-multiple" || ($.browser.msie && !(options[0].attributes['value'].specified) ? options[0].text : options[0].value).length > 0);
What about trying the which
command?
If you were to run which psql
and Postgres is not installed there appears to be no output. You just get the terminal prompt ready to accept another command:
> which psql
>
But if Postgres is installed you'll get a response with the path to the location of the Postgres install:
> which psql
/opt/boxen/homebrew/bin/psql
Looking at man which
there also appears to be an option that could help you out:
-s No output, just return 0 if any of the executables are found, or
1 if none are found.
So it seems like as long as whatever scripting language you're using can can execute a terminal command you could send which -s psql
and use the return value to determine if Postgres is installed. From there you can print that result however you like.
I do have postgres installed on my machine so I run the following
> which -s psql
> echo $?
0
which tells me that the command returned 0, indicating that the Postgres executable was found on my machine.
The correct format for passing variables in a GET request is
?variable1=value1&variable2=value2&variable3=value3...
^ ---notice &--- ^
But essentially, you have the right idea.
You can do something like this:
<html>
<head><title>My Glossary</title></head>
<body style="margin:0px;">
<div id="top" style="position:fixed;background:white;width:100%;">
<a href="#A">A</a> |
<a href="#B">B</a> |
<a href="#Z">Z</a>
</div>
<div id="term-defs" style="padding-top:1em;">
<dl>
<span id="A"></span>
<dt>foo</dt>
<dd>This is the sound made by a fool</dd>
<!-- and so on ... ->
</dl>
</div>
</body>
</html>
It's the position:fixed that's most important, because it takes the top div from the normal page flow and fixes it at it's pre-determined position. It's also important to use the padding-top:1em because otherwise the term-defs div would start right under the top div. The background and width are there to cover the contents of the term-defs div as they scroll under the top div.
Hope this helps.
A note of personal experience in addition to both Stefan Gehrig's answer and Dave None's answer (and mmmshuddup's reply):
I was having validation problems using both \n and PHP_EOL when I used the ICS validator at http://severinghaus.org/projects/icv/
I learned I had to use \r\n in order to get it to validate properly, so this was my solution:
function dateToCal($timestamp) {
return date('Ymd\Tgis\Z', $timestamp);
}
function escapeString($string) {
return preg_replace('/([\,;])/','\\\$1', $string);
}
$eol = "\r\n";
$load = "BEGIN:VCALENDAR" . $eol .
"VERSION:2.0" . $eol .
"PRODID:-//project/author//NONSGML v1.0//EN" . $eol .
"CALSCALE:GREGORIAN" . $eol .
"BEGIN:VEVENT" . $eol .
"DTEND:" . dateToCal($end) . $eol .
"UID:" . $id . $eol .
"DTSTAMP:" . dateToCal(time()) . $eol .
"DESCRIPTION:" . htmlspecialchars($title) . $eol .
"URL;VALUE=URI:" . htmlspecialchars($url) . $eol .
"SUMMARY:" . htmlspecialchars($description) . $eol .
"DTSTART:" . dateToCal($start) . $eol .
"END:VEVENT" . $eol .
"END:VCALENDAR";
$filename="Event-".$id;
// Set the headers
header('Content-type: text/calendar; charset=utf-8');
header('Content-Disposition: attachment; filename=' . $filename);
// Dump load
echo $load;
That stopped my parse errors and made my ICS files validate properly.
Watch Video or Follow the step
Install bootstrap 4 in angular 2 / angular 4 / angular 5 / angular 6
There is three way to include bootstrap in your project
1) Add CDN Link in index.html file
2) Install bootstrap using npm and set path in angular.json Recommended
3) Install bootstrap using npm and set path in index.html file
I recommended you following 2 methods that are installed bootstrap using npm because its installed in your project directory and you can easily access it
Method 1
Add Bootstrap, Jquery and popper.js CDN path to you angular project index.html file
Bootstrap.css
https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
Bootstrap.js
https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
Jquery.js
https://code.jquery.com/jquery-3.2.1.slim.min.js
Popper.js
https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js
Method 2
1) Install bootstrap using npm
npm install bootstrap --save
after the installation of Bootstrap 4, we Need two More javascript Package that is Jquery and Popper.js without these two package bootstrap is not complete because Bootstrap 4 is using Jquery and popper.js package so we have to install as well
2) Install JQUERY
npm install jquery --save
3) Install Popper.js
npm install popper.js --save
Now Bootstrap is Install on you Project Directory inside node_modules Folder
open angular.json this file are available on you angular directory open that file and add the path of bootstrap, jquery, and popper.js files inside styles[] and scripts[] path see the below example
"styles": [
"node_modules/bootstrap/dist/css/bootstrap.min.css",
"styles.css"
],
"scripts": [
"node_modules/jquery/dist/jquery.min.js",
"node_modules/popper.js/dist/umd/popper.min.js",
"node_modules/bootstrap/dist/js/bootstrap.min.js"
],
Note: Don't change a sequence of js file it should be like this
Method 3
Install bootstrap using npm follow Method 2 in method 3 we just set path inside index.html file instead of angular.json file
bootstrap.css
<link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css",
"styles.css">
Jquery.js
<script src="node_modules/jquery/dist/jquery.min.js"><br>
Bootstrap.js
<script src="node_modules/bootstrap/dist/js/bootstrap.min.js"><br>
Popper.js
<script src="node_modules/popper.js/dist/umd/popper.min.js"><br>
Now Bootstrap Working fine Now
One more way would be to use dumpbin from the Visual Studio tools on DLL and look for the appropriate output
dumpbin.exe /HEADERS <your dll path>
FILE HEADER VALUE
14C machine (x86)
4 number of sections
5885AC36 time date stamp Mon Jan 23 12:39:42 2017
0 file pointer to symbol table
0 number of symbols
E0 size of optional header
2102 characteristics
Executable
32 bit word machine
DLL
Note: Above o/p is for 32bit dll
One more useful option with dumpbin.exe is /EXPORTS, It will show you the function exposed by the dll
dumpbin.exe /EXPORTS <PATH OF THE DLL>
For node.js I've found the following to be effective way to wait for an element to no longer be present:
// variable to hold loop limit
var limit = 5;
// variable to hold the loop count
var tries = 0;
var retry = driver.findElements(By.xpath(selector));
while(retry.size > 0 && tries < limit){
driver.sleep(timeout / 10)
tries++;
retry = driver.findElements(By.xpath(selector))
}
Based on Perkins' amazing approach, I've updated and improved his "shortcut" for simple algebraic expressions (no functions or variables). Now it works on Python 3.6+ and avoids some pitfalls:
import re, sys
# Kept outside simple_eval() just for performance
_re_simple_eval = re.compile(rb'd([\x00-\xFF]+)S\x00')
def simple_eval(expr):
c = compile(expr, 'userinput', 'eval')
m = _re_simple_eval.fullmatch(c.co_code)
if not m:
raise ValueError(f"Not a simple algebraic expresion: {expr}")
return c.co_consts[int.from_bytes(m.group(1), sys.byteorder)]
Testing, using some of the examples in other answers:
for expr, res in (
('2^4', 6 ),
('2**4', 16 ),
('1 + 2*3**(4^5) / (6 + -7)', -5.0 ),
('7 + 9 * (2 << 2)', 79 ),
('6 // 2 + 0.0', 3.0 ),
('2+3', 5 ),
('6+4/2*2', 10.0 ),
('3+2.45/8', 3.30625),
('3**3*3/3+3', 30.0 ),
):
result = simple_eval(expr)
ok = (result == res and type(result) == type(res))
print("{} {} = {}".format("OK!" if ok else "FAIL!", expr, result))
OK! 2^4 = 6
OK! 2**4 = 16
OK! 1 + 2*3**(4^5) / (6 + -7) = -5.0
OK! 7 + 9 * (2 << 2) = 79
OK! 6 // 2 + 0.0 = 3.0
OK! 2+3 = 5
OK! 6+4/2*2 = 10.0
OK! 3+2.45/8 = 3.30625
OK! 3**3*3/3+3 = 30.0
Looking at your requirement, there is alternate solution as well. It seems you know the dimensions in dp at compile time, so you can add a dimen entry in the resources. Then you can query the dimen entry and it will be automatically converted to pixels in this call:
final float inPixels= mActivity.getResources().getDimension(R.dimen.dimen_entry_in_dp);
And your dimens.xml will have:
<dimen name="dimen_entry_in_dp">72dp</dimen>
Extending this idea, you can simply store the value of 1dp or 1sp as a dimen entry and query the value and use it as a multiplier. Using this approach you will insulate the code from the math stuff and rely on the library to perform the calculations.
When you are using curl
sometimes give you 403 (access forbidden)
Solved by adding this line to emulate browser.
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)');
Hope this help someone.
Yes, it is because you are using auto layout. Setting the view frame and resizing mask will not work.
You should read Working with Auto Layout Programmatically and Visual Format Language.
You will need to get the current constraints, add the text field, adjust the contraints for the text field, then add the correct constraints on the text field.
You can use:
jQuery('[name="' + nameAttributeValue + '"]');
this will be an inefficient way to select elements though, so it would be best to also use the tag name or restrict the search to a specific element:
jQuery('div[name="' + nameAttributeValue + '"]'); // with tag name
jQuery('div[name="' + nameAttributeValue + '"]',
document.getElementById('searcharea')); // with a search base
Maven will not run your tests if the project has <packaging>pom</packaging>
You need to set the packaging to jar (or some other java artefact type) for the tests to run: <packaging>jar</packaging>
With no argument:
ourObject = PowerMockito.spy(new OurClass());
when(ourObject , "ourPrivateMethodName").thenReturn("mocked result");
With String
argument:
ourObject = PowerMockito.spy(new OurClass());
when(ourObject, method(OurClass.class, "ourPrivateMethodName", String.class))
.withArguments(anyString()).thenReturn("mocked result");
Your code works fine, except that the barplot is ordered from low to high. When you want to order the bars from high to low, you will have to add a -
sign before value
:
ggplot(corr.m, aes(x = reorder(miRNA, -value), y = value, fill = variable)) +
geom_bar(stat = "identity")
which gives:
Used data:
corr.m <- structure(list(miRNA = structure(c(5L, 2L, 3L, 6L, 1L, 4L), .Label = c("mmu-miR-139-5p", "mmu-miR-1983", "mmu-miR-301a-3p", "mmu-miR-5097", "mmu-miR-532-3p", "mmu-miR-96-5p"), class = "factor"),
variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "pos", class = "factor"),
value = c(7L, 75L, 70L, 5L, 10L, 47L)),
class = "data.frame", row.names = c("1", "2", "3", "4", "5", "6"))
You can try using Scanner if you are using JDK5 or higher.
Scanner scan = new Scanner(file);
scan.useDelimiter("\\Z");
String content = scan.next();
Or you can also use Guava
String data = Files.toString(new File("path.txt"), Charsets.UTF8);
To find all the links, we will in this example use the urllib2 module together with the re.module *One of the most powerful function in the re module is "re.findall()". While re.search() is used to find the first match for a pattern, re.findall() finds all the matches and returns them as a list of strings, with each string representing one match*
import urllib2
import re
#connect to a URL
website = urllib2.urlopen(url)
#read html code
html = website.read()
#use re.findall to get all the links
links = re.findall('"((http|ftp)s?://.*?)"', html)
print links
Fortran can handle array, especially multidimensional arrays, very conveniently. Slicing elements of multidimensional array in Fortran can be much easier than that in C/C++. C++ now has libraries can do the job, such as Boost or Eigen, but they are after all external libraries. In Fortran these functions are intrinsic.
Whether Fortran is faster or more convenient for developing mostly depends on the job you need to finish. As a scientific computation person for geophysics, I did most of computation in Fortran (I mean modern Fortran, >=F90).
First uninstall all java software like JRE 7 or JRE 6 or JDK ,then open the following path :
START > CONTROL PANEL > ADVANCED SETTING > ENVIRONMENT VARIABLE > SYSTEM VARIABLE > PATH
Then click on Edit button and paste the following text to Variable_Value and click OK.
C:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\Program Files (x86)\Common Files\Microsoft Shared\Windows Live;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Microsoft SQL Server\90\Tools\binn\;C:\Program Files (x86)\Common Files\Roxio Shared\DLLShared\;C:\Program Files (x86)\Windows Live\Shared;C:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\VSShell\Common7\IDE\;C:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\;C:\Program Files\Microsoft SQL Server\100\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\100\DTS\Binn\
Now go to this url http://java.com/en/download/manual.jsp and click on Windows Offline and click on run and start again eclipse.
Enjoy it!
On a Windows platform,
[mysqld]
section.explicit_defaults_for_timestamp=true
without quotes and save the change.This worked for me (windows 7 Ultimate 32bit)
For people who find this via search engines, you do not need VBA. You can just:
1.) select the query or table with your mouse
2.) click export data from the ribbon
3.) click excel from the export subgroup
4.) follow the wizard to select the output file and location.
The easiest way to do this, as noted by Umar is, for example
mysql> SET GLOBAL time_zone = 'America/New_York';
Using the named timezone is important for timezone that has a daylights saving adjustment. However, for some linux builds you may get the following response:
#1298 - Unknown or incorrect time zone
If you're seeing this, you may need to run a tzinfo_to_sql translation... it's easy to do, but not obvious. From the linux command line type in:
mysql_tzinfo_to_sql /usr/share/zoneinfo/|mysql -u root mysql -p
Provide your root password (MySQL root, not Linux root) and it will load any definitions in your zoneinfo into mysql. You can then go back and run your
mysql> SET GLOBAL time_zone = timezone;
The sqlite team published an article explaining when to use sqlite that is great read. Basically, you want to avoid using sqlite when you have a lot of write concurrency or need to scale to terabytes of data. In many other cases, sqlite is a surprisingly good alternative to a "traditional" database such as MySQL.
This article helped me. I was submitting form via AJAX and forgotten to use return false
(after my ajax request) which led to classic form submission but strangely it was not completed.
To create setup projects in Visual Studio 2012 with InstallShield Limited Edition, watch this video.
The InstallShield limited edition that cannot install services.
"ISLE is by far the worst installer option and the upgraded, read - paid for, version is cumbersome to use at best and impossible in most situations. InnoSetup, Nullsoft, Advanced, WiX, or just about any other installer is better. If you did a survey you would see that nobody is using ISLE. I don't know why you guys continue to associate with InstallShield. It damages your credibility. Any developer worth half his weight in salt knows ISLE is worthless and when you stand behind it we have to question Microsoft's judgment."
By Edward Miller (comments in Visual Studio Installer Projects Extension).
The WiX Toolset, which, while powerful is exceeding user-unfriendly and has a steep learning curve. There is even a downloadable template for installing Windows services (ref. VS2012: Installer for Windows services?).
For Visual Studio 2013, see blog post Creating installers with Visual Studio.
Encapsulation: Is hiding unwanted/un-expected/propriety implementation details from the actual users of object. e.g.
List<string> list = new List<string>();
list.Sort(); /* Here, which sorting algorithm is used and hows its
implemented is not useful to the user who wants to perform sort, that's
why its hidden from the user of list. */
Abstraction: Is a way of providing generalization and hence a common way to work with objects of vast diversity. e.g.
class Aeroplane : IFlyable, IFuelable, IMachine
{ // Aeroplane's Design says:
// Aeroplane is a flying object
// Aeroplane can be fueled
// Aeroplane is a Machine
}
// But the code related to Pilot, or Driver of Aeroplane is not bothered
// about Machine or Fuel. Hence,
// pilot code:
IFlyable flyingObj = new Aeroplane();
flyingObj.Fly();
// fighter Pilot related code
IFlyable flyingObj2 = new FighterAeroplane();
flyingObj2.Fly();
// UFO related code
IFlyable ufoObj = new UFO();
ufoObj.Fly();
// **All the 3 Above codes are genaralized using IFlyable,
// Interface Abstraction**
// Fly related code knows how to fly, irrespective of the type of
// flying object they are.
// Similarly, Fuel related code:
// Fueling an Aeroplane
IFuelable fuelableObj = new Aeroplane();
fuelableObj.FillFuel();
// Fueling a Car
IFuelable fuelableObj2 = new Car(); // class Car : IFuelable { }
fuelableObj2.FillFuel();
// ** Fueling code does not need know what kind of vehicle it is, so far
// as it can Fill Fuel**
To convert the private key from PKCS#1 to PKCS#8 with openssl:
# openssl pkcs8 -topk8 -inform PEM -outform PEM -nocrypt -in pkcs1.key -out pkcs8.key
That will work as long as you have the PKCS#1 key in PEM (text format) as described in the question.
I ran into a similar problem with unit tests (specifically in jest when the unit tests run locally to create the snapshots and then the CI server runs in (potentially) a different timezone causing the snapshot comparison to fail). I mocked our Date
and some of the supporting methods like so:
describe('...', () => {
let originalDate;
beforeEach(() => {
originalDate = Date;
Date = jest.fn(
(d) => {
let newD;
if (d) {
newD = (new originalDate(d));
} else {
newD = (new originalDate('2017-05-29T10:00:00z'));
}
newD.toLocaleString = () => {
return (new originalDate(newD.valueOf())).toLocaleString("en-US", {timeZone: "America/New_York"});
};
newD.toLocaleDateString = () => {
return (new originalDate(newD.valueOf())).toLocaleDateString("en-US", {timeZone: "America/New_York"});
};
newD.toLocaleTimeString = () => {
return (new originalDate(newD.valueOf())).toLocaleTimeString("en-US", {timeZone: "America/New_York"});
};
return newD;
}
);
Date.now = () => { return (Date()); };
});
afterEach(() => {
Date = originalDate;
});
});
Had the same kind of problem and in fact the problem was not the function nor the function call, but what I passed as arguments to the function.
The function was called from the body of the script - the 'main' - so I passed "st1 a b" "st2 c d" "st3 e f" from the command line and passed it over to the function using myFunction $*
The $* causes the problem as it expands into a set of characters which will be interpreted in the call to the function using whitespace as a delimiter.
The solution was to change the call to the function in explicit argument handling from the 'main' towards the function : the call would then be myFunction "$1" "$2" "$3" which will preserve the whitespace inside strings as the quotes will delimit the arguments ... So if a parameter can contain spaces, it should be handled explicitly throughout all calls of functions.
As this may be the reason for long searches to problems, it may be wise never to use $* to pass arguments ...
Hope this helps someone, someday, somewhere ... Jan.
just change them to password('yourpassword')
Javascript cannot typically access local files in new browsers but the XMLHttpRequest object can be used to read files. So it is actually Ajax (and not Javascript) which is reading the file.
If you want to read the file abc.txt
, you can write the code as:
var txt = '';
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.status == 200 && xmlhttp.readyState == 4){
txt = xmlhttp.responseText;
}
};
xmlhttp.open("GET","abc.txt",true);
xmlhttp.send();
Now txt
contains the contents of the file abc.txt.
this can be done very easily with HTML 5, see this link http://www.html5rocks.com/en/tutorials/file/dndfiles/
For MySQL:
SELECT lastname AS ln
FROM
(SELECT lastname, count(*) as Counter
FROM `students`
GROUP BY `lastname`) AS tbl WHERE Counter > 2
Add STATS=10
or STATS=1
in backup command.
BACKUP DATABASE [xxxxxx] TO DISK = N'E:\\Bachup_DB.bak' WITH NOFORMAT, NOINIT,
NAME = N'xxxx-Complète Base de données Sauvegarde', SKIP, NOREWIND, NOUNLOAD, COMPRESSION, STATS = 10
GO.
The correct way to implement your code is
y="HELLO"
val=$(echo "$y" | tr '[:upper:]' '[:lower:]')
string="$val world"
This uses $(...)
notation to capture the output of the command in a variable. Note also the quotation marks around the string
variable -- you need them there to indicate that $val
and world
are a single thing to be assigned to string
.
If you have bash
4.0 or higher, a more efficient & elegant way to do it is to use bash
builtin string manipulation:
y="HELLO"
string="${y,,} world"
Bootstrap 4 progress bar
<div class="progress">
<div class="progress-bar" role="progressbar" style="" aria-valuenow="" aria-valuemin="0" aria-valuemax="100"></div>
</div>
Javascript
change progress bar on next/previous page actions
var count = Number(document.getElementById('count').innerHTML); //set this on page load in a hidden field after an ajax call
var total = document.getElementById('total').innerHTML; //set this on initial page load
var pcg = Math.floor(count/total*100);
document.getElementsByClassName('progress-bar').item(0).setAttribute('aria-valuenow',pcg);
document.getElementsByClassName('progress-bar').item(0).setAttribute('style','width:'+Number(pcg)+'%');
The vroom package provides a 'tidy' method of selecting / dropping columns by name during import. Docs: https://www.tidyverse.org/blog/2019/05/vroom-1-0-0/#column-selection
The vroom argument 'col_select' makes selecting columns to keep (or omit) more straightforward. The interface for col_select is the same as dplyr::select().
Select columns by namedata <- vroom("flights.tsv", col_select = c(year, flight, tailnum))
#> Observations: 336,776
#> Variables: 3
#> chr [1]: tailnum
#> dbl [2]: year, flight
#>
#> Call `spec()` for a copy-pastable column specification
#> Specify the column types with `col_types` to quiet this message
Drop columns by name
data <- vroom("flights.tsv", col_select = c(-dep_time, -air_time:-time_hour))
#> Observations: 336,776
#> Variables: 13
#> chr [4]: carrier, tailnum, origin, dest
#> dbl [9]: year, month, day, sched_dep_time, dep_delay, arr_time, sched_arr_time, arr...
#>
#> Call `spec()` for a copy-pastable column specification
#> Specify the column types with `col_types` to quiet this message
Use the selection helpers
data <- vroom("flights.tsv", col_select = ends_with("time"))
#> Observations: 336,776
#> Variables: 5
#> dbl [5]: dep_time, sched_dep_time, arr_time, sched_arr_time, air_time
#>
#> Call `spec()` for a copy-pastable column specification
#> Specify the column types with `col_types` to quiet this message
Or rename columns by name
data <- vroom("flights.tsv", col_select = list(plane = tailnum, everything()))
#> Observations: 336,776
#> Variables: 19
#> chr [ 4]: carrier, tailnum, origin, dest
#> dbl [14]: year, month, day, dep_time, sched_dep_time, dep_delay, arr_time, sched_arr...
#> dttm [ 1]: time_hour
#>
#> Call `spec()` for a copy-pastable column specification
#> Specify the column types with `col_types` to quiet this message
data
#> # A tibble: 336,776 x 19
#> plane year month day dep_time sched_dep_time dep_delay arr_time
#> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 N142… 2013 1 1 517 515 2 830
#> 2 N242… 2013 1 1 533 529 4 850
#> 3 N619… 2013 1 1 542 540 2 923
#> 4 N804… 2013 1 1 544 545 -1 1004
#> 5 N668… 2013 1 1 554 600 -6 812
#> 6 N394… 2013 1 1 554 558 -4 740
#> 7 N516… 2013 1 1 555 600 -5 913
#> 8 N829… 2013 1 1 557 600 -3 709
#> 9 N593… 2013 1 1 557 600 -3 838
#> 10 N3AL… 2013 1 1 558 600 -2 753
#> # … with 336,766 more rows, and 11 more variables: sched_arr_time <dbl>,
#> # arr_delay <dbl>, carrier <chr>, flight <dbl>, origin <chr>,
#> # dest <chr>, air_time <dbl>, distance <dbl>, hour <dbl>, minute <dbl>,
#> # time_hour <dttm>
What you need is this:
a, b, c = [0,3,5] # Unpack the list, now a, b, and c are ints
a = 1 # `a` did equal 0, not [0,3,5]
print(a)
print(b)
print(c)
I tried many of the methods here, but they were either complicated or didn't quite meet my requirements. In fact, one can write a helper method quite simply:
public class ExceptionAssertions {
public static void assertException(BlastContainer blastContainer ) {
boolean caughtException = false;
try {
blastContainer.test();
} catch( Exception e ) {
caughtException = true;
}
if( !caughtException ) {
throw new AssertionFailedError("exception expected to be thrown, but was not");
}
}
public static interface BlastContainer {
public void test() throws Exception;
}
}
Use it like this:
assertException(new BlastContainer() {
@Override
public void test() throws Exception {
doSomethingThatShouldExceptHere();
}
});
Zero dependencies: no need for mockito, no need powermock; and works just fine with final classes.
Here's an alternative to the accepted answer that works in the current (2.12) version of the API.
<a href="#" onclick="logoutFromFacebookAndRedirect('/logout')">Logout</a>
<script>
FB.init({
appId: '{your-app-id}',
cookie: true,
xfbml: true,
version: 'v2.12'
});
function logoutFromFacebookAndRedirect(redirectUrl) {
FB.getLoginStatus(function (response) {
if (response.status == 'connected')
FB.logout(function (response) {
window.location.href = redirectUrl;
});
else
window.location.href = redirectUrl;
});
}
</script>
Often in Node.js applications a .json is needed. With TypeScript 2.9, --resolveJsonModule allows for importing, extracting types from and generating .json files.
Example #
// tsconfig.json_x000D_
_x000D_
{_x000D_
"compilerOptions": {_x000D_
"module": "commonjs",_x000D_
"resolveJsonModule": true,_x000D_
"esModuleInterop": true_x000D_
}_x000D_
}_x000D_
_x000D_
// .ts_x000D_
_x000D_
import settings from "./settings.json";_x000D_
_x000D_
settings.debug === true; // OK_x000D_
settings.dry === 2; // Error: Operator '===' cannot be applied boolean and number_x000D_
_x000D_
_x000D_
// settings.json_x000D_
_x000D_
{_x000D_
"repo": "TypeScript",_x000D_
"dry": false,_x000D_
"debug": false_x000D_
}
_x000D_
Take a look also at How do I sort unicode strings alphabetically in Python? where the discussion is about sorting rules given by the Unicode Collation Algorithm (http://www.unicode.org/reports/tr10/).
To reply to the comment
What? How else can ordering be defined other than left-to-right?
by S.Lott, there is a famous counter-example when sorting French language. It involves accents: indeed, one could say that, in French, letters are sorted left-to-right and accents right-to-left. Here is the counter-example: we have e < é and o < ô, so you would expect the words cote, coté, côte, côté to be sorted as cote < coté < côte < côté. Well, this is not what happens, in fact you have: cote < côte < coté < côté, i.e., if we remove "c" and "t", we get oe < ôe < oé < ôé, which is exactly right-to-left ordering.
And a last remark: you shouldn't be talking about left-to-right and right-to-left sorting but rather about forward and backward sorting.
Indeed there are languages written from right to left and if you think Arabic and Hebrew are sorted right-to-left you may be right from a graphical point of view, but you are wrong on the logical level!
Indeed, Unicode considers character strings encoded in logical order, and writing direction is a phenomenon occurring on the glyph level. In other words, even if in the word ???? the letter shin appears on the right of the lamed, logically it occurs before it. To sort this word one will first consider the shin, then the lamed, then the vav, then the mem, and this is forward ordering (although Hebrew is written right-to-left), while French accents are sorted backwards (although French is written left-to-right).
You're setting the background of the image to another image. Which is fine, but the foreground (SRC attribute of the IMG) still overlays everything else.
.nkhome{
margin-left:260px;
top:170px;
position:absolute;
}
.nkhome a {
background:url(Images/btnhome.png);
display:block; /* Necessary, since A is not a block element */
width:59px;
height:59px;
}
.nkhome a:hover {
background:url(Images/btnhomeh.png);
}
<div class="nkhome">
<a href="Home.html"></a>
</div>
I wanted to delete all records from both tables because it was all test data. I used SSMS GUI to temporarily disable a FK constraint, then I ran a DELETE query on both tables, and finally I re-enabled the FK constraint.
To disable the FK constraint:
[1] in the 'Object Explorer' pane, can be accessed via the 'View' menu option, or key F8
[2] if you're not sure which table is the dependant one, you can check by right clicking the table in question and selecting the 'View Dependencies' option.
It's permission problem. It is not "classic" read/write permissions of apache user, but selinux one.
Apache cannot write to files labeled as httpd_sys_content_t
they can be only read by apache.
You have 2 possibilities:
label svn repository files as httpd_sys_content_rw_t
:
chcon -R -t httpd_sys_content_rw_t /path/to/your/svn/repo
set selinux boolean httpd_unified --> on
setsebool -P httpd_unified=1
I prefer 2nd possibility. You can play also with other selinux booleans connected with httpd
:
getsebool -a | grep httpd
Solution posted by Denys S. in the question post:
I quite messed it up with c to c++ conversion (basically env
variable stuff), but I got it working with the following code for C++:
#include <string.h>
#include <stdio.h>
#include <jni.h>
jstring Java_the_package_MainActivity_getJniString( JNIEnv* env, jobject obj){
jstring jstr = (*env)->NewStringUTF(env, "This comes from jni.");
jclass clazz = (*env)->FindClass(env, "com/inceptix/android/t3d/MainActivity");
jmethodID messageMe = (*env)->GetMethodID(env, clazz, "messageMe", "(Ljava/lang/String;)Ljava/lang/String;");
jobject result = (*env)->CallObjectMethod(env, obj, messageMe, jstr);
const char* str = (*env)->GetStringUTFChars(env,(jstring) result, NULL); // should be released but what a heck, it's a tutorial :)
printf("%s\n", str);
return (*env)->NewStringUTF(env, str);
}
And next code for java methods:
public class MainActivity extends Activity {
private static String LIB_NAME = "thelib";
static {
System.loadLibrary(LIB_NAME);
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = (TextView) findViewById(R.id.textview);
tv.setText(this.getJniString());
}
// please, let me live even though I used this dark programming technique
public String messageMe(String text) {
System.out.println(text);
return text;
}
public native String getJniString();
}
In my case I had an issue around using Microsoft.ReportViewer.WebForms. I removed validate=true from add verb
line in web.config and it started working:
<system.web>
<httpHandlers>
<add verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
Isn't
$(document).ready(function() {
});
what you are looking for?
You can make use of ArrayList. Array has the fixed number of size.
This Example here can help you. The example is pretty easy with its output.
Output: 2 5 1 23 14
New length: 20
Element at Index 5:29
List size: 6
Removing element at index 2: 1
2 5 23 14 29
Try os.system("pause")
— I used it and it worked for me.
Make sure to include import os
at the top of your script.
Refer to here
write query with named parameter, use simple ListPreparedStatementSetter
with all parameters in sequence. Just add below snippet to convert the query in traditional form based to available parameters,
ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(namedSql);
List<Integer> parameters = new ArrayList<Integer>();
for (A a : paramBeans)
parameters.add(a.getId());
MapSqlParameterSource parameterSource = new MapSqlParameterSource();
parameterSource.addValue("placeholder1", parameters);
// create SQL with ?'s
String sql = NamedParameterUtils.substituteNamedParameters(parsedSql, parameterSource);
return sql;
In laravel 5 you can use dump(), Dump the content from the last response.
class ExampleTest extends TestCase{
public function test1()
{
$this->post('/user', ['name' => 'Gema']);
$this->dump();
}
}
To retrieve it:
cat /proc/sys/kernel/threads-max
To set it:
echo 123456789 | sudo tee -a /proc/sys/kernel/threads-max
123456789 = # of threads
Use SQL Server Migration Assistant (SSMA)
In addition to MySQL it supports Oracle, Sybase and MS Access.
It appears to be quite smart and capable of handling even nontrivial transfers. It also got some command line interface (in addition to GUI) so theoretically it can be integrated into some batch load process.
This the current download link for MySQL version https://www.microsoft.com/en-us/download/details.aspx?id=54257
The current (June 2016) stable version 6.0.1 crashes with the current (5.3.6) MySQL ODBC driver while transferring data. Everything 64 bit. The 5.3 version with the 5.1.13 ODBC driver works fine.
have you tried eager loading?
@attachments = Job.includes(:attachments).find(1).attachments
Here is how you would do it with Apache HttpClient (this solution is for those who don't mind using a 3rd party library):
HttpEntity entity = MultipartEntityBuilder.create()
.addPart("file", new FileBody(file))
.build();
HttpPost request = new HttpPost(url);
request.setEntity(entity);
HttpClient client = HttpClientBuilder.create().build();
HttpResponse response = client.execute(request);
You could use this kind of code :
function toggleChevron(e) {
$(e.target)
.prev('.panel-heading')
.find('i.indicator')
.toggleClass('glyphicon-chevron-down glyphicon-chevron-up');
}
$('#accordion').on('hidden.bs.collapse', toggleChevron);
$('#accordion').on('shown.bs.collapse', toggleChevron);
=> Working JsFiddle
If there are multiple levels of inheritance, you can specify the direct base class, even if the actual implementation is at a lower level.
class Foo
{
public:
virtual void DoStuff ()
{
}
};
class Bar : public Foo
{
};
class Baz : public Bar
{
public:
void DoStuff ()
{
Bar::DoStuff() ;
}
};
In this example, the class Baz specifies Bar::DoStuff() although the class Bar does not contain an implementation of DoStuff. That is a detail, which Baz does not need to know.
It is clearly a better practice to call Bar::DoStuff than Foo::DoStuff, in case a later version of Bar also overrides this method.
If you're looking for the class-level equivalent of @property
, then the answer is "there's no such thing". But remember, @property
is only syntactic sugar, anyway; it just creates appropriately-named object methods.
You want to create class methods that access static variables which, as others have said, have only a slightly different syntax.
Your debut
and fin
values are floating point values, not integers, because taille
is a float.
Make those values integers instead:
item = plateau[int(debut):int(fin)]
Alternatively, make taille
an integer:
taille = int(sqrt(len(plateau)))
append the revision using an "@" character:
svn copy http://src@REV http://dev
Or, use the -r [--revision] command line argument.
Just adding that using the first approach it can be done as -
pd.DataFrame(list(map(list, zip(lst1,lst2,lst3))))
You have a pointer to an object. Therefore, you need to access a field of an object that's pointed to by the pointer. To dereference the pointer you use *
, and to access a field, you use .
, so you can use:
cout << (*kwadrat).val1;
Note that the parentheses are necessary. This operation is common enough that long ago (when C was young) they decided to create a "shorthand" method of doing it:
cout << kwadrat->val1;
These are defined to be identical. As you can see, the ->
basically just combines a *
and a .
into a single operation. If you were dealing directly with an object or a reference to an object, you'd be able to use the .
without dereferencing a pointer first:
Kwadrat kwadrat2(2,3,4);
cout << kwadrat2.val1;
The ::
is the scope resolution operator. It is used when you only need to qualify the name, but you're not dealing with an individual object at all. This would be primarily to access a static data member:
struct something {
static int x; // this only declares `something::x`. Often found in a header
};
int something::x; // this defines `something::x`. Usually in .cpp/.cc/.C file.
In this case, since x
is static
, it's not associated with any particular instance of something
. In fact, it will exist even if no instance of that type of object has been created. In this case, we can access it with the scope resolution operator:
something::x = 10;
std::cout << something::x;
Note, however, that it's also permitted to access a static member as if it was a member of a particular object:
something s;
s.x = 1;
At least if memory serves, early in the history of C++ this wasn't allowed, but the meaning is unambiguous, so they decided to allow it.
import pytest
class Test:
@pytest.fixture()
def setUp(self):
print("setup")
yield "resource"
print("teardown")
def test_that_depends_on_resource(self, setUp):
print("testing {}".format(setUp))
In order to run:
pytest nam_of_the_module.py -v
var sessionVal = '@Session["EnergyUnit"]';
alert(sessionVal);
Note, that starting from PostgreSQL 8.4 you can get all information about sequences used in the database via:
SELECT * FROM information_schema.sequences;
Since I'm using a higher version of PostgreSQL (9.1), and was searching for same answer high and low, I added this answer for posterity's sake and for future searchers.
From a layout perspective, it is possible using modern techniques.
Its made up (I believe) by Heydon Pickering. He details the process here: http://www.heydonworks.com/article/the-flexbox-holy-albatross
Chris Coyier picks it up and works through a demo of it here: https://css-tricks.com/putting-the-flexbox-albatross-to-real-use/
To restate the issue, below we see 3 of the same component, each made up of three orange divs labelled a
, b
and c
.
The second two's blocks display vertically, because they are limited on horizontal room, while the top components 3 blocks are laid out horizontally.
It uses the flex-basis
CSS property and CSS Variables to create this effect.
.panel{
display: flex;
flex-wrap: wrap;
border: 1px solid #f00;
$breakpoint: 600px;
--multiplier: calc( #{$breakpoint} - 100%);
.element{
min-width: 33%;
max-width: 100%;
flex-grow: 1;
flex-basis: calc( var(--multiplier) * 999 );
}
}
Heydon's article is 1000 words explaining it in detail, and I'd highly recommend reading it.
Whenever you want to execute an SQL statement that shouldn't return a value or a record set, the ExecuteNonQuery should be used.
So if you want to run an update, delete, or insert statement, you should use the ExecuteNonQuery. ExecuteNonQuery returns the number of rows affected by the statement. This sounds very nice, but whenever you use the SQL Server 2005 IDE or Visual Studio to create a stored procedure it adds a small line that ruins everything.
That line is: SET NOCOUNT ON; This line turns on the NOCOUNT feature of SQL Server, which "Stops the message indicating the number of rows affected by a Transact-SQL statement from being returned as part of the results" and therefore it makes the stored procedure always to return -1 when called from the application (in my case a web application).
In conclusion, remove that line from your stored procedure, and you will now get a value indicating the number of rows affected by the statement.
Happy programming!
A pool of threads means that all your threads are running, all the time – in other words, the thread function never returns. To give the threads something meaningful to do, you have to design a system of inter-thread communication, both for the purpose of telling the thread that there's something to do, as well as for communicating the actual work data.
Typically this will involve some kind of concurrent data structure, and each thread would presumably sleep on some kind of condition variable, which would be notified when there's work to do. Upon receiving the notification, one or several of the threads wake up, recover a task from the concurrent data structure, process it, and store the result in an analogous fashion.
The thread would then go on to check whether there's even more work to do, and if not go back to sleep.
The upshot is that you have to design all this yourself, since there isn't a natural notion of "work" that's universally applicable. It's quite a bit of work, and there are some subtle issues you have to get right. (You can program in Go if you like a system which takes care of thread management for you behind the scenes.)
If you want to reduce the size to decimal(7,2) from decimal(9,2) you will have to account for the existing data with values greater to fit into decimal(7,2). Either you will have to delete those numbers are truncate it down to fit into your new size. If there was no data for the field you are trying to update it will do it automatically without issues
wait() works fine for me. The subprocesses p1, p2 and p3 are executed at the same. Therefore, all processes are done after 3 seconds.
import subprocess
processes = []
p1 = subprocess.Popen("sleep 3", stdout=subprocess.PIPE, shell=True)
p2 = subprocess.Popen("sleep 3", stdout=subprocess.PIPE, shell=True)
p3 = subprocess.Popen("sleep 3", stdout=subprocess.PIPE, shell=True)
processes.append(p1)
processes.append(p2)
processes.append(p3)
for p in processes:
if p.wait() != 0:
print("There was an error")
print("all processed finished")
I strongly disagree with some previous solutions that recommended to run both services in the same container. It's clearly stated in the documentation that it's not a recommended:
It is generally recommended that you separate areas of concern by using one service per container. That service may fork into multiple processes (for example, Apache web server starts multiple worker processes). It’s ok to have multiple processes, but to get the most benefit out of Docker, avoid one container being responsible for multiple aspects of your overall application. You can connect multiple containers using user-defined networks and shared volumes.
There are good use cases for supervisord or similar programs but running a web application + database is not part of them.
You should definitely use docker-compose to do that and orchestrate multiple containers with different responsibilities.