For me the issue was that I had not included the Entity Class within my db set inside the context for entity framework.
public DbSet<ModelName> ModelName { get; set; }
There can be multiple root causes for this exception. For me, my mockMvc wasn't getting auto-configured. I solved this exception by using @WebMvcTest(MyController.class)
at the class level. This annotation will disable full auto-configuration and instead apply only configuration relevant to MVC tests.
An alternative to this is, If you are looking to load your full application configuration and use MockMVC, you should consider @SpringBootTest
combined with @AutoConfigureMockMvc
rather than @WebMvcTest
My guess is that you simply need to URL-encode your Base64 string when you include it in the querystring.
Base64 encoding uses some characters which must be encoded if they're part of a querystring (namely +
and /
, and maybe =
too). If the string isn't correctly encoded then you won't be able to decode it successfully at the other end, hence the errors.
You can use the HttpUtility.UrlEncode
method to encode your Base64 string:
string msg = "Please click on the link below or paste it into a browser "
+ "to verify your email account.<br /><br /><a href=\""
+ _configuration.RootURL + "Accounts/VerifyEmail.aspx?a="
+ HttpUtility.UrlEncode(userName.Encrypt("verify")) + "\">"
+ _configuration.RootURL + "Accounts/VerifyEmail.aspx?a="
+ HttpUtility.UrlEncode(userName.Encrypt("verify")) + "</a>";
If you don't care about checking the validity of the certificate just add the --no-check-certificate
option on the wget command-line. This worked well for me.
NOTE: This opens you up to man-in-the-middle (MitM) attacks, and is not recommended for anything where you care about security.
<pre lang="xml" >{{xmlString}}</pre>
This worked for me. Thanks to http://www.codeproject.com/Answers/998872/Display-XML-in-HTML-Div#answer1
Those saying that you can't safely remove an item from a collection except through the Iterator aren't quite correct, you can do it safely using one of the concurrent collections such as ConcurrentHashMap.
The property IsOneWay=true
may be true in the Operational contract of the interface.
Remove that property to get rid of this error.
Here is my example:
private List<int> m_machinePorts = new List<int>();
public List<int> machinePorts
{
get { return m_machinePorts; }
}
Init()
{
// Custom function to get available ethernet ports
List<int> localEnetPorts = _Globals.GetAvailableEthernetPorts();
// Custome function to get available serial ports
List<int> localPorts = _Globals.GetAvailableSerialPorts();
// Build Available port list
m_machinePorts.AddRange(localEnetPorts);
m_machinePorts.AddRange(localPorts);
}
Configure NLog via XML, but Programmatically
What? Did you know that you can specify the NLog XML directly to NLog from your app, as opposed to having NLog read it from the config file? Well, you can. Let's say that you have a distributed app and you want to use the same configuration everywhere. You could keep a config file in each location and maintain it separately, you could maintain one in a central location and push it out to the satellite locations, or you could probably do a lot of other things. Or, you could store your XML in a database, get it at app startup, and configure NLog directly with that XML (maybe checking back periodically to see if it had changed).
string xml = @"<nlog>
<targets>
<target name='console' type='Console' layout='${message}' />
</targets>
<rules>
<logger name='*' minlevel='Error' writeTo='console' />
</rules>
</nlog>";
StringReader sr = new StringReader(xml);
XmlReader xr = XmlReader.Create(sr);
XmlLoggingConfiguration config = new XmlLoggingConfiguration(xr, null);
LogManager.Configuration = config;
//NLog is now configured just as if the XML above had been in NLog.config or app.config
logger.Trace("Hello - Trace"); //Won't log
logger.Debug("Hello - Debug"); //Won't log
logger.Info("Hello - Info"); //Won't log
logger.Warn("Hello - Warn"); //Won't log
logger.Error("Hello - Error"); //Will log
logger.Fatal("Hello - Fatal"); //Will log
//Now let's change the config (the root logging level) ...
string xml2 = @"<nlog>
<targets>
<target name='console' type='Console' layout='${message}' />
</targets>
<rules>
<logger name='*' minlevel='Trace' writeTo='console' />
</rules>
</nlog>";
StringReader sr2 = new StringReader(xml2);
XmlReader xr2 = XmlReader.Create(sr2);
XmlLoggingConfiguration config2 = new XmlLoggingConfiguration(xr2, null);
LogManager.Configuration = config2;
logger.Trace("Hello - Trace"); //Will log
logger.Debug("Hello - Debug"); //Will log
logger.Info("Hello - Info"); //Will log
logger.Warn("Hello - Warn"); //Will log
logger.Error("Hello - Error"); //Will log
logger.Fatal("Hello - Fatal"); //Will log
I'm not sure how robust this is, but this example provides a useful starting point for people that might want to try configuring like this.
Try using join on a str conversion of your ints:
print(' '.join(str(x) for x in array))
For python 3.7
I created a PS script to check idle time and jiggle the mouse to prevent the screensaver.
There are two parameters you can control how it works.
$checkIntervalInSeconds
: the interval in seconds to check if the idle time exceeds the limit
$preventIdleLimitInSeconds
: the idle time limit in seconds. If the idle time exceeds the idle time limit, jiggle the mouse to prevent the screensaver
Here we go. Save the script in preventIdle.ps1
. For preventing the 4-min screensaver, I
set $checkIntervalInSeconds = 30
and $preventIdleLimitInSeconds = 180
.
Add-Type @'
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace PInvoke.Win32 {
public static class UserInput {
[DllImport("user32.dll", SetLastError=false)]
private static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
[StructLayout(LayoutKind.Sequential)]
private struct LASTINPUTINFO {
public uint cbSize;
public int dwTime;
}
public static DateTime LastInput {
get {
DateTime bootTime = DateTime.UtcNow.AddMilliseconds(-Environment.TickCount);
DateTime lastInput = bootTime.AddMilliseconds(LastInputTicks);
return lastInput;
}
}
public static TimeSpan IdleTime {
get {
return DateTime.UtcNow.Subtract(LastInput);
}
}
public static double IdleSeconds {
get {
return IdleTime.TotalSeconds;
}
}
public static int LastInputTicks {
get {
LASTINPUTINFO lii = new LASTINPUTINFO();
lii.cbSize = (uint)Marshal.SizeOf(typeof(LASTINPUTINFO));
GetLastInputInfo(ref lii);
return lii.dwTime;
}
}
}
}
'@
Add-Type @'
using System;
using System.Runtime.InteropServices;
namespace MouseMover
{
public class MouseSimulator
{
[DllImport("user32.dll", SetLastError = true)]
static extern uint SendInput(uint nInputs, ref INPUT pInputs, int cbSize);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetCursorPos(out POINT lpPoint);
[StructLayout(LayoutKind.Sequential)]
struct INPUT
{
public SendInputEventType type;
public MouseKeybdhardwareInputUnion mkhi;
}
[StructLayout(LayoutKind.Explicit)]
struct MouseKeybdhardwareInputUnion
{
[FieldOffset(0)]
public MouseInputData mi;
[FieldOffset(0)]
public KEYBDINPUT ki;
[FieldOffset(0)]
public HARDWAREINPUT hi;
}
[StructLayout(LayoutKind.Sequential)]
struct KEYBDINPUT
{
public ushort wVk;
public ushort wScan;
public uint dwFlags;
public uint time;
public IntPtr dwExtraInfo;
}
[StructLayout(LayoutKind.Sequential)]
struct HARDWAREINPUT
{
public int uMsg;
public short wParamL;
public short wParamH;
}
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
public int X;
public int Y;
public POINT(int x, int y)
{
this.X = x;
this.Y = y;
}
}
struct MouseInputData
{
public int dx;
public int dy;
public uint mouseData;
public MouseEventFlags dwFlags;
public uint time;
public IntPtr dwExtraInfo;
}
[Flags]
enum MouseEventFlags : uint
{
MOUSEEVENTF_MOVE = 0x0001
}
enum SendInputEventType : int
{
InputMouse
}
public static void MoveMouseBy(int x, int y) {
INPUT mouseInput = new INPUT();
mouseInput.type = SendInputEventType.InputMouse;
mouseInput.mkhi.mi.dwFlags = MouseEventFlags.MOUSEEVENTF_MOVE;
mouseInput.mkhi.mi.dx = x;
mouseInput.mkhi.mi.dy = y;
SendInput(1, ref mouseInput, Marshal.SizeOf(mouseInput));
}
}
}
'@
$checkIntervalInSeconds = 30
$preventIdleLimitInSeconds = 180
while($True) {
if (([PInvoke.Win32.UserInput]::IdleSeconds -ge $preventIdleLimitInSeconds)) {
[MouseMover.MouseSimulator]::MoveMouseBy(10,0)
[MouseMover.MouseSimulator]::MoveMouseBy(-10,0)
}
Start-Sleep -Seconds $checkIntervalInSeconds
}
Then, open Windows PowerShell and run
powershell -ExecutionPolicy ByPass -File C:\SCRIPT-DIRECTORY-PATH\preventIdle.ps1
The answers of installing pip via:
curl https://bootstrap.pypa.io/get-pip.py |sudo python
or curl https://bootstrap.pypa.io/get-pip.py | python
did not work for me as I kept on getting the error:
Could not fetch URL https://pypi.org/simple/pip/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/pip/ (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)) - skipping
ERROR: Could not find a version that satisfies the requirement pip (from versions: none)
ERROR: No matching distribution found for pip
I had to install pip
manually via:
pip
distribution websitetar.gz
versioncd
into the directorypython setup.py install
Editor warning: This solution is computationally inefficient and may bring down your connection for a large table.
NB - You need to do this first on a test copy of your table!
When I did it, I found that unless I also included AND n1.id <> n2.id
, it deleted every row in the table.
If you want to keep the row with the lowest id
value:
DELETE n1 FROM names n1, names n2 WHERE n1.id > n2.id AND n1.name = n2.name
If you want to keep the row with the highest id
value:
DELETE n1 FROM names n1, names n2 WHERE n1.id < n2.id AND n1.name = n2.name
I used this method in MySQL 5.1
Not sure about other versions.
Update: Since people Googling for removing duplicates end up here
Although the OP's question is about DELETE
, please be advised that using INSERT
and DISTINCT
is much faster. For a database with 8 million rows, the below query took 13 minutes, while using DELETE
, it took more than 2 hours and yet didn't complete.
INSERT INTO tempTableName(cellId,attributeId,entityRowId,value)
SELECT DISTINCT cellId,attributeId,entityRowId,value
FROM tableName;
You would have to script the View like below. You would essentially write the results of your proc to a table var or temp table, then select into the view.
Edit - If you can change your stored procedure to a Table Value function, it would eliminate the step of selecting to a temp table.
**Edit 2 ** - Comments are correct that a sproc cannot be read into a view like I suggested. Instead, convert your proc to a table-value function as mentioned in other posts and select from that:
create view sampleView
as select field1, field2, ...
from dbo.MyTableValueFunction
I apologize for the confusion
get matched string back or false
function preg_match (regex, str) {
if (new RegExp(regex).test(str)){
return regex.exec(str);
}
return false;
}
I think you need to use for example:
aws ecs list-container-instances --cluster default --region us-east-1
This depends of your region of course.
Another approach which seemed to work for me at least in Linux environment is to run your Node.js application like this:
env TZ='Europe/Amsterdam' node server.js
This should at least ensure that the timezone is correctly set already from the beginning.
I made a super simple class to handle this in a Mac application I'm working on. Hopefully, this is helpful to someone
RadioButtonController Class:
class RadioButtonController: NSObject {
var buttonArray : [NSButton] = []
var currentleySelectedButton : NSButton?
var defaultButton : NSButton = NSButton() {
didSet {
buttonArrayUpdated(buttonSelected: self.defaultButton)
}
}
func buttonArrayUpdated(buttonSelected : NSButton) {
for button in buttonArray {
if button == buttonSelected {
currentleySelectedButton = button
button.state = .on
} else {
button.state = .off
}
}
}
}
Implementation in View Controller:
class OnboardingDefaultLaunchConfiguration: NSViewController {
let radioButtonController : RadioButtonController = RadioButtonController()
@IBOutlet weak var firstRadioButton: NSButton!
@IBOutlet weak var secondRadioButton: NSButton!
@IBAction func folderRadioButtonSelected(_ sender: Any) {
radioButtonController.buttonArrayUpdated(buttonSelected: folderGroupRadioButton)
}
@IBAction func fileListRadioButtonSelected(_ sender: Any) {
radioButtonController.buttonArrayUpdated(buttonSelected: fileListRadioButton)
}
override func viewDidLoad() {
super.viewDidLoad()
radioButtonController.buttonArray = [firstRadioButton, secondRadioButton]
radioButtonController.defaultButton = firstRadioButton
}
}
I'am trying to install SQL SERVER developer 2008 R2 alongside SQL SERVER 2005 EXPRESS,
i went to program features, clicked on unistall SQL SERVER 2005 EXPRESS, and only checked, WORKSTATION COMPONENTS, it unistalled: support files, sql mngmt studio
After that installation of sql 2008 r2 developer went ok....
Hopes this helps somebody
You can use the following to only include valid characters:
SQL
SELECT * FROM @Table
WHERE Col NOT LIKE '%[^0-9.]%'
Results
Col
---------
234.62
6435.23
2
Further to PhoneixS answer to get the correct length of string in bytes - Since mb_strlen()
is slower than strlen()
, for the best performance one can check "mbstring.func_overload" ini setting so that mb_strlen()
is used only when it is really required:
$content_length = ini_get('mbstring.func_overload') ? mb_strlen($content , '8bit') : strlen($content);
You may want to look at how you can use the built-in features of .NET to serialize and deserialize an object into XML, rather than creating a ToXML()
method on every class that is essentially just a Data Transfer Object.
I have used these techniques successfully on a couple of projects but don’t have the implementation details handy right now. I will try to update my answer with my own examples sometime later.
Here's a couple of examples that Google returned:
XML Serialization in .NET by Venkat Subramaniam http://www.agiledeveloper.com/articles/XMLSerialization.pdf
How to Serialize and Deserialize an object into XML http://www.dotnetfunda.com/articles/article98.aspx
Customize your .NET object XML serialization with .NET XML attributes http://blogs.microsoft.co.il/blogs/rotemb/archive/2008/07/27/customize-your-net-object-xml-serialization-with-net-xml-attributes.aspx
See Python 3.x format string syntax:
IDLE 3.5.1
numbers = ['23.23', '.1233', '1', '4.223', '9887.2']
for x in numbers:
print('{0: >#016.4f}'. format(float(x)))
23.2300
0.1233
1.0000
4.2230
9887.2000
This working fine as per my requirement
<ImageView
android:id="@+id/imgIssue"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="fitXY"/>
$(function(){
$('input').keyup(function(){
var input_val = $(this).val();
var inputRGEX = /^[a-zA-Z0-9]*$/;
var inputResult = inputRGEX.test(input_val);
if(!(inputResult))
{
this.value = this.value.replace(/[^a-z0-9\s]/gi, '');
}
});
});
Try this:
function SelectAnimal()
{
var animals = document.getElementById('Animals');
var animalsToFind = document.getElementById('AnimalToFind');
// get the options length
var len = animals.options.length;
for(i = 0; i < len; i++)
{
// check the current option's text if it's the same with the input box
if (animals.options[i].innerHTML == animalsToFind.value)
{
animals.selectedIndex = i;
break;
}
}
}
I did somewhat for my application as it:
Below is the query:
select distinct i.userId,i.statusCheck, l.userName from internetstatus
as i inner join login as l on i.userID=l.userID
where nowtime in((select max(nowtime) from InternetStatus group by userID));
According to Apple’s user experience coding guide for mobile Safari, you can use the following to display a numeric keyboard in the iPhone browser:
<input type="text" pattern="[0-9]*" />
A pattern
of \d*
will also work.
Mutable means that it can change/mutate. Immutable the opposite.
Some Python data types are mutable, others not.
Let's find what are the types that fit in each category and see some examples.
Mutable
In Python there are various mutable types:
lists
dict
set
Let's see the following example for lists
.
list = [1, 2, 3, 4, 5]
If I do the following to change the first element
list[0] = '!'
#['!', '2', '3', '4', '5']
It works just fine, as lists are mutable.
If we consider that list, that was changed, and assign a variable to it
y = list
And if we change an element from the list such as
list[0] = 'Hello'
#['Hello', '2', '3', '4', '5']
And if one prints y
it will give
['Hello', '2', '3', '4', '5']
As both list
and y
are referring to the same list, and we have changed the list.
Immutable
In some programming languages one can define a constant such as the following
const a = 10
And if one calls, it would give an error
a = 20
However, that doesn't exist in Python.
In Python, however, there are various immutable types:
None
bool
int
float
str
tuple
Let's see the following example for strings
.
Taking the string a
a = 'abcd'
We can get the first element with
a[0]
#'a'
If one tries to assign a new value to the element in the first position
a[0] = '!'
It will give an error
'str' object does not support item assignment
When one says += to a string, such as
a += 'e'
#'abcde'
It doesn't give an error, because it is pointing a
to a different string.
It would be the same as the following
a = a + 'f'
And not changing the string.
Some Pros and Cons of being immutable
• The space in memory is known from the start. It would not require extra space.
• Usually, it makes things more efficiently. Finding, for example, the len()
of a string is much faster, as it is part of the string object.
See: Local dependency in package.json
It looks like the answer is npm link
: https://docs.npmjs.com/cli/link
The reason is that your rule
%.o: %.cpp
...
expects the .cpp file to reside in the same directory as the .o your building. Since test.exe in your case depends on build/widgets/apple.o (etc), make is expecting apple.cpp to be build/widgets/apple.cpp.
You can use VPATH to resolve this:
VPATH = src/widgets
BUILDDIR = build/widgets
$(BUILDDIR)/%.o: %.cpp
...
When attempting to build "build/widgets/apple.o", make will search for apple.cpp in VPATH. Note that the build rule has to use special variables in order to access the actual filename make finds:
$(BUILDDIR)/%.o: %.cpp
$(CC) $< -o $@
Where "$<" expands to the path where make located the first dependency.
Also note that this will build all the .o files in build/widgets. If you want to build the binaries in different directories, you can do something like
build/widgets/%.o: %.cpp
....
build/ui/%.o: %.cpp
....
build/tests/%.o: %.cpp
....
I would recommend that you use "canned command sequences" in order to avoid repeating the actual compiler build rule:
define cc-command
$(CC) $(CFLAGS) $< -o $@
endef
You can then have multiple rules like this:
build1/foo.o build1/bar.o: %.o: %.cpp
$(cc-command)
build2/frotz.o build2/fie.o: %.o: %.cpp
$(cc-command)
For more information. I try setting src attribute with attr method in jquery for ad image using the syntax for example: $("#myid").attr('src', '/images/sample.gif');
This solution is useful and it works but if changing the path change also the path for image and not working.
I've searching for resolve this issue but not found nothing.
The solution is putting the '\' at the beginning the path:
$("#myid").attr('src', '\images/sample.gif');
This trick is very useful for me and I hope it is useful for other.
To deal with any type of files for my own APP, I use this configuration for CFBundleDocumentTypes:
<key>CFBundleDocumentTypes</key>
<array>
<dict>
<key>CFBundleTypeName</key>
<string>IPA</string>
<key>LSItemContentTypes</key>
<array>
<string>public.item</string>
<string>public.content</string>
<string>public.data</string>
<string>public.database</string>
<string>public.composite-content</string>
<string>public.contact</string>
<string>public.archive</string>
<string>public.url-name</string>
<string>public.text</string>
<string>public.plain-text</string>
<string>public.source-code</string>
<string>public.executable</string>
<string>public.script</string>
<string>public.shell-script</string>
<string>public.xml</string>
<string>public.symlink</string>
<string>org.gnu.gnu-zip-archve</string>
<string>org.gnu.gnu-tar-archive</string>
<string>public.image</string>
<string>public.movie</string>
<string>public.audiovisual-?content</string>
<string>public.audio</string>
<string>public.directory</string>
<string>public.folder</string>
<string>com.apple.bundle</string>
<string>com.apple.package</string>
<string>com.apple.plugin</string>
<string>com.apple.application-?bundle</string>
<string>com.pkware.zip-archive</string>
<string>public.filename-extension</string>
<string>public.mime-type</string>
<string>com.apple.ostype</string>
<string>com.apple.nspboard-typ</string>
<string>com.adobe.pdf</string>
<string>com.adobe.postscript</string>
<string>com.adobe.encapsulated-?postscript</string>
<string>com.adobe.photoshop-?image</string>
<string>com.adobe.illustrator.ai-?image</string>
<string>com.compuserve.gif</string>
<string>com.microsoft.word.doc</string>
<string>com.microsoft.excel.xls</string>
<string>com.microsoft.powerpoint.?ppt</string>
<string>com.microsoft.waveform-?audio</string>
<string>com.microsoft.advanced-?systems-format</string>
<string>com.microsoft.advanced-?stream-redirector</string>
<string>com.microsoft.windows-?media-wmv</string>
<string>com.microsoft.windows-?media-wmp</string>
<string>com.microsoft.windows-?media-wma</string>
<string>com.apple.keynote.key</string>
<string>com.apple.keynote.kth</string>
<string>com.truevision.tga-image</string>
</array>
<key>CFBundleTypeIconFiles</key>
<array>
<string>Icon-76@2x</string>
</array>
</dict>
</array>
This is how I have done it, I have tested it in both Firefox and Chrome. This makes it possible to check the filename and line number of the place where the function is called from.
logFileAndLineNumber(new Error());
function logFileAndLineNumber(newErr)
{
if(navigator.userAgent.indexOf("Firefox") != -1)
{
var originPath = newErr.stack.split('\n')[0].split("/");
var fileNameAndLineNumber = originPath[originPath.length - 1].split(">")[0];
console.log(fileNameAndLineNumber);
}else if(navigator.userAgent.indexOf("Chrome") != -1)
{
var originFile = newErr.stack.split('\n')[1].split('/');
var fileName = originFile[originFile.length - 1].split(':')[0];
var lineNumber = originFile[originFile.length - 1].split(':')[1];
console.log(fileName+" line "+lineNumber);
}
}
You can use std::find
as follows:
if (std::find(v.begin(), v.end(), "abc") != v.end())
{
// Element in vector.
}
To be able to use std::find
: include <algorithm>
.
This is an old post but the shortest answer is not listed here so I am adding it now
strtr($str,[' '=>'']);
Another common way to "skin this cat" would be to use explode and implode like this
implode('',explode(' ', $str));
Here's a javasript tool that will convert JSON to XML and vice versa, which should enhance its readability. You could then create a style sheet to color it or do a complete transform to HTML.
http://www.xml.com/pub/a/2006/05/31/converting-between-xml-and-json.html
ISO_8859_1 Worked for me! I was reading text file with comma separated values
You need to escape the backslash \
:
println yourString.replace("\\", "/")
set -x
is fine.
Another way to print each executed command is to use trap
with DEBUG
.
Put this line at the beginning of your script :
trap 'echo "# $BASH_COMMAND"' DEBUG
You can find a lot of other trap
usages here.
There are a lot of right answers here, but many of the "regex" are incomplete and it can happen that an email like: "name@domain" results a valid email, but it is not. Here the complete solution:
extension String {
var isEmailValid: Bool {
do {
let regex = try NSRegularExpression(pattern: "(?:[a-z0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[a-z0-9!#$%\\&'*+/=?\\^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])", options: .CaseInsensitive)
return regex.firstMatchInString(self, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, self.characters.count)) != nil
} catch {
return false
}
}
}
You could (but you shouldn't) use reflection for the job:
import java.lang.reflect.Field;
public class Outer {
public class Inner {
}
public static void main(String[] args) throws Exception {
// Create the inner instance
Inner inner = new Outer().new Inner();
// Get the implicit reference from the inner to the outer instance
// ... make it accessible, as it has default visibility
Field field = Inner.class.getDeclaredField("this$0");
field.setAccessible(true);
// Dereference and cast it
Outer outer = (Outer) field.get(inner);
System.out.println(outer);
}
}
Of course, the name of the implicit reference is utterly unreliable, so as I said, you shouldn't :-)
I am using this which works if you pass it a date obj or js timestamp:
getHumanReadableDate: function(date) {
if (date instanceof Date) {
return date.getDate() + "/" + (date.getMonth() + 1) + "/" + date.getFullYear();
} else if (isFinite(date)) {//timestamp
var d = new Date();
d.setTime(date);
return this.getHumanReadableDate(d);
}
}
I don't think you should do this.
The POST is, as you know, to modify the collection and it's used to CREATE a new item. So, if you send the id (I think it's not a good idea), you should modify the collection, i.e., modify the item, but it's confusing.
Use it to add an item, without id. It's the best practice.
If you want to capture an UNIQUE constraint (not the id) you can response 409, as you can do in PUT requests. But not the ID.
httpListener.Prefixes.Add("http://*:4444/");
you use "*" so you execute following cmd as admin
netsh http add urlacl url=http://*:4444/ user=username
no use +, must use *, because you spec *:4444~.
https://msdn.microsoft.com/en-us/library/system.net.httplistener.aspx
If you don't have Java 8, and agree with me that including a massive library to avoid writing a few lines of code is a bad idea:
public static byte[] readBytes(InputStream inputStream) throws IOException {
byte[] b = new byte[1024];
ByteArrayOutputStream os = new ByteArrayOutputStream();
int c;
while ((c = inputStream.read(b)) != -1) {
os.write(b, 0, c);
}
return os.toByteArray();
}
Caller is responsible for closing the stream.
Other way could be this one:
driver.FindElement(By.XPath(".//*[@id='examp']/form/select[1]/option[3]")).Click();
and you can change the index in option[x] changing x by the number of element that you want to select.
I don't know if it is the best way but I hope that help you.
A couple of wires are crossed here. The various autoplay
settings that you're working with only affect whether the SWF's root timeline starts out paused or not. So if your SWF had a timeline animation, or if it had an embedded video on the root timeline, then these settings would do what you're after.
However, the SWF you're working with almost certainly has only one frame on its timeline, so these settings won't affect playback at all. That one frame contains some flavor of video playback component, which contains ActionScript that controls how the video behaves. To get that player component to start of paused, you'll have to change the settings of the component itself.
Without knowing more about where the content came from it's hard to say more, but when one publishes from Flash, video player components normally include a parameter for whether to autoplay. If your SWF is being published by an application other than Flash (Captivate, I suppose, but I'm not up on that) then your best bet would be to check the settings for that app. Anyway it's not something you can control from the level of the HTML page. (Unless you were talking to the SWF from JavaScript, and for that to work the video component would have to be designed to allow it.)
I believe this would be somewhere close.
INSERT INTO Files
(FileId, FileData)
SELECT 1, * FROM OPENROWSET(BULK N'C:\Image.jpg', SINGLE_BLOB) rs
Something to note, the above runs in SQL Server 2005 and SQL Server 2008 with the data type as varbinary(max)
. It was not tested with image as data type.
There are some guys at Mozilla working on implementing a PDF reader using HTML5 and JavaScript. It is called pdf.js and one of the developers just made an interesting blog post about the project.
Unset will destroy a particular session variable whereas session_destroy()
will destroy all the session data for that user.
It really depends on your application as to which one you should use. Just keep the above in mind.
unset($_SESSION['name']); // will delete just the name data
session_destroy(); // will delete ALL data associated with that user.
as a reminder: if you are using edittext.setSelection()
to set the cursor, and it is NOT working while setting up an alertdialog
for example, make sure to set the selection()
AFTER the dialog has been created
example:
AlertDialog dialog = builder.show();
input.setSelection(x,y);
After doing it both ways for a few projects my stance is that composer.lock
should not be committed as part of the project.
composer.lock
is build metadata which is not part of the project. The state of dependencies should be controlled through how you're versioning them (either manually or as part of your automated build process) and not arbitrarily by the last developer to update them and commit the lock file.
If you are concerned about your dependencies changing between composer updates then you have a lack of confidence in your versioning scheme. Versions (1.0, 1.1, 1.2, etc) should be immutable and you should avoid "dev-" and "X.*" wildcards outside of initial feature development.
Committing the lock file is a regression for your dependency management system as the dependency version has now gone back to being implicitly defined.
Also, your project should never have to be rebuilt or have its dependencies reacquired in each environment, especially prod. Your deliverable (tar, zip, phar, a directory, etc) should be immutable and promoted through environments without changing.
var x = 2;
for(o in window){
if(window[o] === x){
alert(o);
}
}
However, I think you should do like "karim79"
You can also get this error when you have an infinite loop. Make sure that you don't have any unending, recursive self references.
The way you are doing it is indeed the recommended one (for Python 2.x).
The issue of whether the class is passed explicitly to super
is a matter of style rather than functionality. Passing the class to super
fits in with Python's philosophy of "explicit is better than implicit".
My guess is that you are trying to restore in lower versions which wont work
For me this was the solution.
The problem was that the SVN server was behind a reverse-proxy (pound). And the reverse proxy had to be told to allow OPTIONS
.
Shortest version to prettify existing JSON: (edit: using JSON.net)
JToken.Parse("mystring").ToString()
Input:
{"menu": { "id": "file", "value": "File", "popup": { "menuitem": [ {"value": "New", "onclick": "CreateNewDoc()"}, {"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"} ] } }}
Output:
{
"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{
"value": "New",
"onclick": "CreateNewDoc()"
},
{
"value": "Open",
"onclick": "OpenDoc()"
},
{
"value": "Close",
"onclick": "CloseDoc()"
}
]
}
}
}
To pretty-print an object:
JToken.FromObject(myObject).ToString()
Following solution is better than bootbox.js, because
digimango.messagebox.js:
const dialogTemplate = '\_x000D_
<div class ="modal" id="digimango_messageBox" role="dialog">\_x000D_
<div class ="modal-dialog">\_x000D_
<div class ="modal-content">\_x000D_
<div class ="modal-body">\_x000D_
<p class ="text-success" id="digimango_messageBoxMessage">Some text in the modal.</p>\_x000D_
<p><textarea id="digimango_messageBoxTextArea" cols="70" rows="5"></textarea></p>\_x000D_
</div>\_x000D_
<div class ="modal-footer">\_x000D_
<button type="button" class ="btn btn-primary" id="digimango_messageBoxOkButton">OK</button>\_x000D_
<button type="button" class ="btn btn-default" data-dismiss="modal" id="digimango_messageBoxCancelButton">Cancel</button>\_x000D_
</div>\_x000D_
</div>\_x000D_
</div>\_x000D_
</div>';_x000D_
_x000D_
_x000D_
// See the comment inside function digimango_onOkClick(event) {_x000D_
var digimango_numOfDialogsOpened = 0;_x000D_
_x000D_
_x000D_
function messageBox(msg, significance, options, actionConfirmedCallback) {_x000D_
if ($('#digimango_MessageBoxContainer').length == 0) {_x000D_
var iDiv = document.createElement('div');_x000D_
iDiv.id = 'digimango_MessageBoxContainer';_x000D_
document.getElementsByTagName('body')[0].appendChild(iDiv);_x000D_
$("#digimango_MessageBoxContainer").html(dialogTemplate);_x000D_
}_x000D_
_x000D_
var okButtonName, cancelButtonName, showTextBox, textBoxDefaultText;_x000D_
_x000D_
if (options == null) {_x000D_
okButtonName = 'OK';_x000D_
cancelButtonName = null;_x000D_
showTextBox = null;_x000D_
textBoxDefaultText = null;_x000D_
} else {_x000D_
okButtonName = options.okButtonName;_x000D_
cancelButtonName = options.cancelButtonName;_x000D_
showTextBox = options.showTextBox;_x000D_
textBoxDefaultText = options.textBoxDefaultText;_x000D_
}_x000D_
_x000D_
if (showTextBox == true) {_x000D_
if (textBoxDefaultText == null)_x000D_
$('#digimango_messageBoxTextArea').val('');_x000D_
else_x000D_
$('#digimango_messageBoxTextArea').val(textBoxDefaultText);_x000D_
_x000D_
$('#digimango_messageBoxTextArea').show();_x000D_
}_x000D_
else_x000D_
$('#digimango_messageBoxTextArea').hide();_x000D_
_x000D_
if (okButtonName != null)_x000D_
$('#digimango_messageBoxOkButton').html(okButtonName);_x000D_
else_x000D_
$('#digimango_messageBoxOkButton').html('OK');_x000D_
_x000D_
if (cancelButtonName == null)_x000D_
$('#digimango_messageBoxCancelButton').hide();_x000D_
else {_x000D_
$('#digimango_messageBoxCancelButton').show();_x000D_
$('#digimango_messageBoxCancelButton').html(cancelButtonName);_x000D_
}_x000D_
_x000D_
$('#digimango_messageBoxOkButton').unbind('click');_x000D_
$('#digimango_messageBoxOkButton').on('click', { callback: actionConfirmedCallback }, digimango_onOkClick);_x000D_
_x000D_
$('#digimango_messageBoxCancelButton').unbind('click');_x000D_
$('#digimango_messageBoxCancelButton').on('click', digimango_onCancelClick);_x000D_
_x000D_
var content = $("#digimango_messageBoxMessage");_x000D_
_x000D_
if (significance == 'error')_x000D_
content.attr('class', 'text-danger');_x000D_
else if (significance == 'warning')_x000D_
content.attr('class', 'text-warning');_x000D_
else_x000D_
content.attr('class', 'text-success');_x000D_
_x000D_
content.html(msg);_x000D_
_x000D_
if (digimango_numOfDialogsOpened == 0)_x000D_
$("#digimango_messageBox").modal();_x000D_
_x000D_
digimango_numOfDialogsOpened++;_x000D_
}_x000D_
_x000D_
function digimango_onOkClick(event) {_x000D_
// JavaScript's nature is unblocking. So the function call in the following line will not block,_x000D_
// thus the last line of this function, which is to hide the dialog, is executed before user_x000D_
// clicks the "OK" button on the second dialog shown in the callback. Therefore we need to count_x000D_
// how many dialogs is currently showing. If we know there is still a dialog being shown, we do_x000D_
// not execute the last line in this function._x000D_
if (typeof (event.data.callback) != 'undefined')_x000D_
event.data.callback($('#digimango_messageBoxTextArea').val());_x000D_
_x000D_
digimango_numOfDialogsOpened--;_x000D_
_x000D_
if (digimango_numOfDialogsOpened == 0)_x000D_
$('#digimango_messageBox').modal('hide');_x000D_
}_x000D_
_x000D_
function digimango_onCancelClick() {_x000D_
digimango_numOfDialogsOpened--;_x000D_
_x000D_
if (digimango_numOfDialogsOpened == 0)_x000D_
$('#digimango_messageBox').modal('hide');_x000D_
}
_x000D_
To use digimango.messagebox.js:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
<title>A useful generic message box</title>_x000D_
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />_x000D_
_x000D_
<link rel="stylesheet" type="text/css" href="~/Content/bootstrap.min.css" media="screen" />_x000D_
<script src="~/Scripts/jquery-1.10.2.min.js" type="text/javascript"></script>_x000D_
<script src="~/Scripts/bootstrap.js" type="text/javascript"></script>_x000D_
<script src="~/Scripts/bootbox.js" type="text/javascript"></script>_x000D_
_x000D_
<script src="~/Scripts/digimango.messagebox.js" type="text/javascript"></script>_x000D_
_x000D_
_x000D_
<script type="text/javascript">_x000D_
function testAlert() {_x000D_
messageBox('Something went wrong!', 'error');_x000D_
}_x000D_
_x000D_
function testAlertWithCallback() {_x000D_
messageBox('Something went wrong!', 'error', null, function () {_x000D_
messageBox('OK clicked.');_x000D_
});_x000D_
}_x000D_
_x000D_
function testConfirm() {_x000D_
messageBox('Do you want to proceed?', 'warning', { okButtonName: 'Yes', cancelButtonName: 'No' }, function () {_x000D_
messageBox('Are you sure you want to proceed?', 'warning', { okButtonName: 'Yes', cancelButtonName: 'No' });_x000D_
});_x000D_
}_x000D_
_x000D_
function testPrompt() {_x000D_
messageBox('How do you feel now?', 'normal', { showTextBox: true }, function (userInput) {_x000D_
messageBox('User entered "' + userInput + '".');_x000D_
});_x000D_
}_x000D_
_x000D_
function testPromptWithDefault() {_x000D_
messageBox('How do you feel now?', 'normal', { showTextBox: true, textBoxDefaultText: 'I am good!' }, function (userInput) {_x000D_
messageBox('User entered "' + userInput + '".');_x000D_
});_x000D_
}_x000D_
_x000D_
</script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<a href="#" onclick="testAlert();">Test alert</a> <br/>_x000D_
<a href="#" onclick="testAlertWithCallback();">Test alert with callback</a> <br />_x000D_
<a href="#" onclick="testConfirm();">Test confirm</a> <br/>_x000D_
<a href="#" onclick="testPrompt();">Test prompt</a><br />_x000D_
<a href="#" onclick="testPromptWithDefault();">Test prompt with default text</a> <br />_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
First, I downloaded a test TIFF image from this page called a_image.tif
. Then I opened with PIL like this:
>>> from PIL import Image
>>> im = Image.open('a_image.tif')
>>> im.show()
This showed the rainbow image. To convert to a numpy array, it's as simple as:
>>> import numpy
>>> imarray = numpy.array(im)
We can see that the size of the image and the shape of the array match up:
>>> imarray.shape
(44, 330)
>>> im.size
(330, 44)
And the array contains uint8
values:
>>> imarray
array([[ 0, 1, 2, ..., 244, 245, 246],
[ 0, 1, 2, ..., 244, 245, 246],
[ 0, 1, 2, ..., 244, 245, 246],
...,
[ 0, 1, 2, ..., 244, 245, 246],
[ 0, 1, 2, ..., 244, 245, 246],
[ 0, 1, 2, ..., 244, 245, 246]], dtype=uint8)
Once you're done modifying the array, you can turn it back into a PIL image like this:
>>> Image.fromarray(imarray)
<Image.Image image mode=L size=330x44 at 0x2786518>
You should use a Func<string, int>
delegate, that represents a function taking a string
argument and returning an int
value:
public bool RunTheMethod(Func<string, int> myMethod)
{
// Do stuff
myMethod.Invoke("My String");
// Do stuff
return true;
}
Then invoke it this way:
public bool Test()
{
return RunTheMethod(Method1);
}
i had sometime ago the same issue. make sure that your ssh key doesn't have password and use not common user account (e.g. better to user account called jenkins or so).
check following article http://fourkitchens.com/blog/2011/09/20/trigger-jenkins-builds-pushing-github
A very simple solution:
df <- read.csv("df.csv",sep=",",head=T)
x <- cbind(df$Xax,df$Xax,df$Xax,df$Xax)
y <- cbind(df$A,df$B,df$C,df$D)
matplot(x,y,type="p")
please note it just plots the data and it does not plot any regression line.
Answer below is what I created to link html contents from another shared drive to the html page I would send out to managers. Of course, the path is relative to your using, but in my case, I would just send them the html, and everything else that is updated from load runner dynamically would be updated for me. Saves tons of paper, and they can play with the numbers as they see fit instead of just a hard copy this way.
SRC="file://///shareddrive/shareddrive-folder/username/scripting/testReport\contents.html" NAME="contents_frame" title="Table of Contents"
The application is a server which simply runs until the system shuts down or it receives a Ctrl+C or the console window is closed.
Due to the extraordinary nature of the application, it is not feasible to "gracefully" exit. (It may be that I could code another application which would send a "server shutdown" message but that would be overkill for one application and still insufficient for certain circumstances like when the server (Actual OS) is actually shutting down.)
Because of these circumstances I added a "ConsoleCtrlHandler" where I stop my threads and clean up my COM objects etc...
Public Declare Auto Function SetConsoleCtrlHandler Lib "kernel32.dll" (ByVal Handler As HandlerRoutine, ByVal Add As Boolean) As Boolean
Public Delegate Function HandlerRoutine(ByVal CtrlType As CtrlTypes) As Boolean
Public Enum CtrlTypes
CTRL_C_EVENT = 0
CTRL_BREAK_EVENT
CTRL_CLOSE_EVENT
CTRL_LOGOFF_EVENT = 5
CTRL_SHUTDOWN_EVENT
End Enum
Public Function ControlHandler(ByVal ctrlType As CtrlTypes) As Boolean
.
.clean up code here
.
End Function
Public Sub Main()
.
.
.
SetConsoleCtrlHandler(New HandlerRoutine(AddressOf ControlHandler), True)
.
.
End Sub
This setup seems to work out perfectly. Here is a link to some C# code for the same thing.
Classic example "Index in Books"
Consider a "Book" of 1000 pages, divided by 10 Chapters, each section with 100 pages.
Simple, huh?
Now, imagine you want to find a particular Chapter that contains a word "Alchemist". Without an index page, you have no other option than scanning through the entire book/Chapters. i.e: 1000 pages.
This analogy is known as "Full Table Scan" in database world.
But with an index page, you know where to go! And more, to lookup any particular Chapter that matters, you just need to look over the index page, again and again, every time. After finding the matching index you can efficiently jump to that chapter by skipping the rest.
But then, in addition to actual 1000 pages, you will need another ~10 pages to show the indices, so totally 1010 pages.
Thus, the index is a separate section that stores values of indexed column + pointer to the indexed row in a sorted order for efficient look-ups.
Things are simple in schools, isn't it? :P
As per my knowledge, finish function close the current displayed screen only.
Refer this example (where see the answer given by 'plusminus'), it will sure help you to close your application.
Using your data:
test_data <- data.frame(
var0 = 100 + c(0, cumsum(runif(49, -20, 20))),
var1 = 150 + c(0, cumsum(runif(49, -10, 10))),
Dates = seq.Date(as.Date("2002-01-01"), by="1 month", length.out=100))
I create a stacked version which is what ggplot()
would like to work with:
stacked <- with(test_data,
data.frame(value = c(var0, var1),
variable = factor(rep(c("Var0","Var1"),
each = NROW(test_data))),
Dates = rep(Dates, 2)))
In this case producing stacked
was quite easy as we only had to do a couple of manipulations, but reshape()
and the reshape
and reshape2
might be useful if you have a more complex real data set to manipulate.
Once the data are in this stacked form, it only requires a simple ggplot()
call to produce the plot you wanted with all the extras (one reason why higher-level plotting packages like lattice
and ggplot2
are so useful):
require(ggplot2)
p <- ggplot(stacked, aes(Dates, value, colour = variable))
p + geom_line()
I'll leave it to you to tidy up the axis labels, legend title etc.
HTH
You can use Date.getTime()
function, or the Date
object itself which when divided returns the time in milliseconds.
var d = new Date();
d/1000
> 1510329641.84
d.getTime()/1000
> 1510329641.84
The typical way is with scanf
:
int input_value;
scanf("%d", &input_value);
In most cases, however, you want to check whether your attempt at reading input succeeded. scanf
returns the number of items it successfully converted, so you typically want to compare the return value against the number of items you expected to read. In this case you're expecting to read one item, so:
if (scanf("%d", &input_value) == 1)
// it succeeded
else
// it failed
Of course, the same is true of all the scanf
family (sscanf
, fscanf
and so on).
Yarn supports this feature:
# .yarnrc file in project root
--modules-folder /node_modules
But your experience can vary depending on which packages you use. I'm not sure you'd want to go into that rabbit hole.
Something like this (not tested, but should work)
Pass this as parameter in Html:
<input type="text" placeholder="some text" class="search" onkeydown="search(this)"/>
And alert the value of the parameter passed into the search function:
function search(e){
alert(e.value);
}
Use the change event of the select:
$('#my_select').change(function()
{
$(this).parents('td').css('background', '#000000');
});
You have to check unique identifier column and you have to give a diff value to that particular field if you give the same value it will not work. It enforces uniqueness of the key.
Here is the code:
Insert into production.product
(Name,ProductNumber,MakeFlag,FinishedGoodsFlag,Color,SafetyStockLevel,ReorderPoint,StandardCost,ListPrice,Size
,SizeUnitMeasureCode,WeightUnitMeasureCode,Weight,DaysToManufacture,
ProductLine,
Class,
Style ,
ProductSubcategoryID
,ProductModelID
,SellStartDate
,SellEndDate
,DiscontinuedDate
,rowguid
,ModifiedDate
)
values ('LL lemon' ,'BC-1234',0,0,'blue',400,960,0.00,100.00,Null,Null,Null,null,1,null,null,null,null,null,'1998-06-01 00:00:00.000',null,null,'C4244F0C-ABCE-451B-A895-83C0E6D1F468','2004-03-11 10:01:36.827')
$file = '../image.jpg';
if (file_exists($file))
{
$size = getimagesize($file);
$fp = fopen($file, 'rb');
if ($size and $fp)
{
// Optional never cache
// header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');
// header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
// header('Pragma: no-cache');
// Optional cache if not changed
// header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($file)).' GMT');
// Optional send not modified
// if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) and
// filemtime($file) == strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']))
// {
// header('HTTP/1.1 304 Not Modified');
// }
header('Content-Type: '.$size['mime']);
header('Content-Length: '.filesize($file));
fpassthru($fp);
exit;
}
}
Unless you have Excel installed on the Server/PC or use an external tool (which is possible without using Excel Interop, see Create Excel (.XLS and .XLSX) file from C#), it will fail. Using the interop requires Excel to be installed.
To answer this point:
I want Sleep to be an async method so it can await other methods
you can maybe rewrite the Sleep
function like this:
private static async Task<int> Sleep(int ms)
{
Console.WriteLine("Sleeping for " + ms);
var task = Task.Run(() => Thread.Sleep(ms));
await task;
Console.WriteLine("Sleeping for " + ms + "END");
return ms;
}
static void Main(string[] args)
{
Console.WriteLine("Starting");
var task1 = Sleep(2000);
var task2 = Sleep(1000);
int totalSlept = task1.Result +task2.Result;
Console.WriteLine("Slept for " + totalSlept + " ms");
Console.ReadKey();
}
running this code will output :
Starting
Sleeping for 2000
Sleeping for 1000
*(one second later)*
Sleeping for 1000END
*(one second later)*
Sleeping for 2000END
Slept for 3000 ms
The key error generally comes if the key doesn't match any of the dataframe column name 'exactly':
You could also try:
import csv
import pandas as pd
import re
with open (filename, "r") as file:
df = pd.read_csv(file, delimiter = ",")
df.columns = ((df.columns.str).replace("^ ","")).str.replace(" $","")
print(df.columns)
I believe the answer above is incorrect, the proper way to initialize with multiple values would be this...
int[] otherList ={1,2,3,4,5};
so the full answer with the proper initialization would look like this
int[] otherList ={1,2,3,4,5};
arList.addAll(Arrays.asList(otherList));
CLARIFICATION
When this question was asked the OP did not say that he wanted the number of LOGICAL cores rather than the actual number of cores, so this answer logically (no pun intended) answers with a way to get the actual number of real physical cores, not the number that the OS tries to virtualize through hyperthreading voodoo.
UPDATE TO HANDLE FLAW IN YOSEMITE
Due to a weird bug in OS X Yosemite (and possibly newer versions, such as the upcoming El Capitan), I've made a small modification. (The old version still worked perfectly well if you just ignore STDERR, which is all the modification does for you.)
Every other answer given here either
bundle install --jobs 3
where you want the number in place of 3
to be one less than the number of cores you've got, or at least not more than the number of cores)The way to get just the number of cores, reliably, correctly, reasonably quickly, and without extra information or even extra characters around the answer, is this:
system_profiler SPHardwareDataType 2> /dev/null | grep 'Total Number of Cores' | cut -d: -f2 | tr -d ' '
You can do it without any interruption, with the new (Git 2.0 Q2 2014) setting gc.autodetach
.
See commit 4c4ac4d and commit 9f673f9 (Nguy?n Thái Ng?c Duy, aka pclouds):
gc --auto
takes time and can block the user temporarily (but not any less annoyingly).
Make it run in background on systems that support it.
The only thing lost with running in background is printouts. Butgc output
is not really interesting.
You can keep it in foreground by changinggc.autodetach
.
Since that 2.0 release, there was a bug though: git 2.7 (Q4 2015) will make sure to not lose the error message.
See commit 329e6e8 (19 Sep 2015) by Nguy?n Thái Ng?c Duy (pclouds
).
(Merged by Junio C Hamano -- gitster
-- in commit 076c827, 15 Oct 2015)
gc
: save log from daemonizedgc --auto
and print it next timeWhile commit 9f673f9 (
gc
: config option for running--auto
in background - 2014-02-08) helps reduce some complaints about 'gc --auto
' hogging the terminal, it creates another set of problems.The latest in this set is, as the result of daemonizing,
stderr
is closed and all warnings are lost. This warning at the end ofcmd_gc()
is particularly important because it tells the user how to avoid "gc --auto
" running repeatedly.
Because stderr is closed, the user does not know, naturally they complain about 'gc --auto
' wasting CPU.Daemonized
gc
now savesstderr
to$GIT_DIR/gc.log
.
Followinggc --auto
will not run andgc.log
printed out until the user removesgc.log
.
I think it is telling you exactly what is wrong. You cannot compare an integer with a varchar. PostgreSQL is strict and does not do any magic typecasting for you. I'm guessing SQLServer does typecasting automagically (which is a bad thing).
If you want to compare these two different beasts, you will have to cast one to the other using the casting syntax ::
.
Something along these lines:
create view view1
as
select table1.col1,table2.col1,table3.col3
from table1
inner join
table2
inner join
table3
on
table1.col4::varchar = table2.col5
/* Here col4 of table1 is of "integer" type and col5 of table2 is of type "varchar" */
/* ERROR: operator does not exist: integer = character varying */
....;
Notice the varchar
typecasting on the table1.col4.
Also note that typecasting might possibly render your index on that column unusable and has a performance penalty, which is pretty bad. An even better solution would be to see if you can permanently change one of the two column types to match the other one. Literately change your database design.
Or you could create a index on the casted values by using a custom, immutable function which casts the values on the column. But this too may prove suboptimal (but better than live casting).
You can post requests directly from the browser with ReqBin. No plugin or desktop app is required.
Visit https://www.tutorialspoint.com/python/string_join.htm
s=" "
seq=["ab", "cd", "ef"]
print(s.join(seq))
ab cd ef
s="."
print(s.join(seq))
ab.cd.ef
This indicates the linux has delivered a SIGTERM
to your process. This is usually at the request of some other process (via kill()
) but could also be sent by your process to itself (using raise()
). This signal requests an orderly shutdown of your process.
If you need a quick cheatsheet of signal numbers, open a bash shell and:
$ kill -l
1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL
5) SIGTRAP 6) SIGABRT 7) SIGBUS 8) SIGFPE
9) SIGKILL 10) SIGUSR1 11) SIGSEGV 12) SIGUSR2
13) SIGPIPE 14) SIGALRM 15) SIGTERM 16) SIGSTKFLT
17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP
21) SIGTTIN 22) SIGTTOU 23) SIGURG 24) SIGXCPU
25) SIGXFSZ 26) SIGVTALRM 27) SIGPROF 28) SIGWINCH
29) SIGIO 30) SIGPWR 31) SIGSYS 34) SIGRTMIN
35) SIGRTMIN+1 36) SIGRTMIN+2 37) SIGRTMIN+3 38) SIGRTMIN+4
39) SIGRTMIN+5 40) SIGRTMIN+6 41) SIGRTMIN+7 42) SIGRTMIN+8
43) SIGRTMIN+9 44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12
47) SIGRTMIN+13 48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14
51) SIGRTMAX-13 52) SIGRTMAX-12 53) SIGRTMAX-11 54) SIGRTMAX-10
55) SIGRTMAX-9 56) SIGRTMAX-8 57) SIGRTMAX-7 58) SIGRTMAX-6
59) SIGRTMAX-5 60) SIGRTMAX-4 61) SIGRTMAX-3 62) SIGRTMAX-2
63) SIGRTMAX-1 64) SIGRTMAX
You can determine the sender by using an appropriate signal handler like:
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
void sigterm_handler(int signal, siginfo_t *info, void *_unused)
{
fprintf(stderr, "Received SIGTERM from process with pid = %u\n",
info->si_pid);
exit(0);
}
int main (void)
{
struct sigaction action = {
.sa_handler = NULL,
.sa_sigaction = sigterm_handler,
.sa_mask = 0,
.sa_flags = SA_SIGINFO,
.sa_restorer = NULL
};
sigaction(SIGTERM, &action, NULL);
sleep(60);
return 0;
}
Notice that the signal handler also includes a call to exit()
. It's also possible for your program to continue to execute by ignoring the signal, but this isn't recommended in general (if it's a user doing it there's a good chance it will be followed by a SIGKILL if your process doesn't exit, and you lost your opportunity to do any cleanup then).
maybe it has a different solution, but I fixed it by finding mysqld.exe and running following command in the console:
C:\wamp\bin\mysql\mysql5.6.17\bin\mysqld.exe --console
You should be able to see following result:
protected void grvSecondaryLocations_RowEditing(object sender, GridViewEditEventArgs e)
{
grvSecondaryLocations.EditIndex = e.NewEditIndex;
DropDownList ddlPbx = (DropDownList)(grvSecondaryLocations.Rows[grvSecondaryLocations.EditIndex].FindControl("ddlPBXTypeNS"));
if (ddlPbx != null)
{
ddlPbx.DataSource = _pbxTypes;
ddlPbx.DataBind();
}
.... (more stuff)
}
The &&
function is not vectorized. You need the &
function:
EUR <- PCs[which(PCs$V13 < 9 & PCs$V13 > 3), ]
I fixed it with Datejs
This is alerting the first day:
var fd = Date.today().clearTime().moveToFirstDayOfMonth();
var firstday = fd.toString("MM/dd/yyyy");
alert(firstday);
This is for the last day:
var ld = Date.today().clearTime().moveToLastDayOfMonth();
var lastday = ld.toString("MM/dd/yyyy");
alert(lastday);
What if you make use of procedural function instead of variable and call them any where as you.
I usually make a collection of configuration values and put them inside a function with return statement. I just include that where I need to make use of global value and call particular function.
function host()
{
return "localhost";
}
A short answer in what context the 3 options are used:
To keep the current changes in the code but to rewrite the commit history:
soft
: You can commit everything at once and create a new commit with a new description (if you use torotise git or any most other GUIs, this is the one to use, as you can still tick which files you want in the commit and make multiple commits that way with different files. In Sourcetree all files would be staged for commit.)mixed
: You will have to add the individual files again to the index before you make commits (in Sourcetree all the changed files would be unstaged)To actually lose your changes in the code as well:
hard
: you don't just rewrite history but also lose all your changes up to the point you resetAnother option is to create a shortcut with the following properties:
Target should be:
"%SYSTEMDRIVE%\Program Files (x86)\Git\bin\sh.exe" --login
Start in is the folder you wish your Git Bash prompt to launch into.
Template literals are also a valid option here, and provide a few benefits.
You can include raw strings, numbers, boolean values, etc:
let request = new Request(`https://example.com/?name=${'Patrick'}&number=${1}`);
You can include variables:
let request = new Request(`https://example.com/?name=${nameParam}`);
You can include logic and functions:
let request = new Request(`https://example.com/?name=${nameParam !== undefined ? nameParam : getDefaultName() }`);
As far as structuring the data of a larger query string, I like using an array concatenated to a string. I find it easier to understand than some of the other methods:
let queryString = [
`param1=${getParam(1)}`,
`param2=${getParam(2)}`,
`param3=${getParam(3)}`,
].join('&');
let request = new Request(`https://example.com/?${queryString}`, {
method: 'GET'
});
Option 1: Likely fastest (but not supported by some browsers if used on Document or SVGElement) :
var elements = document.getElementById('parentContainer').children;
Option 2: Likely slowest :
var elements = document.getElementById('parentContainer').getElementsByTagName('*');
Option 3: Requires change to code (wrap a form instead of a div around it) :
// Since what you're doing looks like it should be in a form...
var elements = document.forms['parentContainer'].elements;
var matches = [];
for (var i = 0; i < elements.length; i++)
if (elements[i].value.indexOf('q17_') == 0)
matches.push(elements[i]);
set Culture to english from web.config file
<globalization uiCulture="en-US" culture="en-US" />
for example if you set the culture to arabic the thime will be
?22?/09?/2017? 02:16:57 ?
and you get the error:Conversion failed when converting date and/or time from character string while inserting datetime
In ECMAScript 5 you have new approach in iteration fields of literal - Object.keys
More information you can see on MDN
My choice is below as a faster solution in current versions of browsers (Chrome30, IE10, FF25)
var keys = Object.keys(p),
len = keys.length,
i = 0,
prop,
value;
while (i < len) {
prop = keys[i];
value = p[prop];
i += 1;
}
You can compare performance of this approach with different implementations on jsperf.com:
Browser support you can see on Kangax's compat table
For old browser you have simple and full polyfill
UPD:
performance comparison for all most popular cases in this question on perfjs.info
:
You can convert directly via the String(byte[], String) constructor and getBytes(String) method. Java exposes available character sets via the Charset class. The JDK documentation lists supported encodings.
90% of the time, such conversions are performed on streams, so you'd use the Reader/Writer classes. You would not incrementally decode using the String methods on arbitrary byte streams - you would leave yourself open to bugs involving multibyte characters.
That is because Low
is a string.
.toFixed()
only works with a number.
Try doing:
Low = parseFloat(Low).toFixed(..);
document.cookie = "cookie_name=cookie_value; max-age=31536000; path=/";
Will set the value for a year.
I think checking keypress
events is not completely adequate, as I believe users can copy/paste into input boxes without triggering a keypress.
So onblur
is probably somewhat more reliable (but is less immediate).
To truly make sure characters you don't want are not entered into input boxes (or textareas, etc.), I think you will need to
keypress
(if you want to give immediate feedback) and onblur
, The code samples in the other answers will work fine for doing the client-side checks (just don't rely only on checking keypress
events), but as was pointed out in the accepted answer, a server-side check is really required.
In drawable I use this xml code to define the border and background:
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke android:width="4dp" android:color="#D8FDFB" />
<padding android:left="7dp" android:top="7dp"
android:right="7dp" android:bottom="7dp" />
<corners android:radius="4dp" />
<solid android:color="#f0600000"/>
</shape>
An example might have been useful, but if I understood you correctly, this would work:
echo "Hello: world" | cut -f1 -d":"
This will convert Hello: world
into Hello
.
I had the same problem several times. The following solutions are solved my problem. I have listed out them according to complexity.
Restart the computer and see whether the problem is out
If it still exists, try to kill the process on running port usually 8080
netstat -ano | findstr 8080
taskkill /F /PID <PID>
If it still exists, go to 'android' directory as follow and go further
cd android
./gradlew clean
and start node
npm start
then run npx react-native run android
or expo stat
and press 'a'
Hope you will OK with the above issues.
If you have a select element that looks like this:
<select id="ddlViewBy">
<option value="1">test1</option>
<option value="2" selected="selected">test2</option>
<option value="3">test3</option>
</select>
Running this code:
var e = document.getElementById("ddlViewBy");
var strUser = e.value;
Would make strUser
be 2
. If what you actually want is test2
, then do this:
var e = document.getElementById("ddlViewBy");
var strUser = e.options[e.selectedIndex].text;
Which would make strUser
be test2
If you want to access your page's global variables, you can do so:
@{
ViewData["Title"] = "Home Page";
var LoadingButtons = Model.ToDictionary(person => person, person => false);
string GetLoadingState (string person) => LoadingButtons[person] ? "is-loading" : string.Empty;
}
>>> a = 5
>>> li = [1, 2, 3]
>>> [a] + li # Don't use 'list' as variable name.
[5, 1, 2, 3]
If anyone else that finds this question and needs a dynamic solution for this where you have an undefined number of columns to transpose to and not exactly 3, you can find a nice solution here: https://github.com/jumpstarter-io/colpivot
Your controller method should be like this:
@RequestMapping(value = " /<your mapping>/{id}", method=RequestMethod.GET)
public String listNotes(@PathVariable("id")int id,Model model) {
Person person = personService.getCurrentlyAuthenticatedUser();
int id = 2323; // Currently passing static values for testing
model.addAttribute("person", new Person());
model.addAttribute("listPersons", this.personService.listPersons());
model.addAttribute("listNotes",this.notesService.listNotesBySectionId(id,person));
return "note";
}
Use the id
in your code, call the controller method from your JSP as:
/{your mapping}/{your id}
UPDATE:
Change your jsp code to:
<c:forEach items="${listNotes}" var="notices" varStatus="status">
<tr>
<td>${notices.noticesid}</td>
<td>${notices.notetext}</td>
<td>${notices.notetag}</td>
<td>${notices.notecolor}</td>
<td>${notices.sectionid}</td>
<td>${notices.canvasid}</td>
<td>${notices.canvasnName}</td>
<td>${notices.personid}</td>
<td><a href="<c:url value='/editnote/${listNotes[status.index].noticesid}' />" >Edit</a></td>
<td><a href="<c:url value='/removenote/${listNotes[status.index].noticesid}' />" >Delete</a></td>
</tr>
</c:forEach>
Wikipedia never lets down:
I feel like this is the simplest way. (Feel free to change the width and height values).
<a href="http://www.google.com"
target="popup"
onclick="window.open('http://www.google.com','popup','width=600,height=600'); return false;">
Link Text goes here...
</a>
My Script:
op_needed = [];
callback_func = function(val) {
var i, j, len;
results = [];
for (j = 0, len = val.length; j < len; j++) {
i = val[j];
if (i['children'].length !== 0) {
call_func(i['children']);
} else {
op_needed.push(i['rel_path']);
}
}
return op_needed;
};
Input JSON:
[
{
"id": null,
"name": "output",
"asset_type_assoc": [],
"rel_path": "output",
"children": [
{
"id": null,
"name": "output",
"asset_type_assoc": [],
"rel_path": "output/f1",
"children": [
{
"id": null,
"name": "v#",
"asset_type_assoc": [],
"rel_path": "output/f1/ver",
"children": []
}
]
}
]
}
]
Function Call:
callback_func(inp_json);
Output as per my Need:
["output/f1/ver"]
In order to access the files, the permissions must be given in the manifest file.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Try this:
String path = Environment.getExternalStorageDirectory().toString()+"/Pictures";
Log.d("Files", "Path: " + path);
File directory = new File(path);
File[] files = directory.listFiles();
Log.d("Files", "Size: "+ files.length);
for (int i = 0; i < files.length; i++)
{
Log.d("Files", "FileName:" + files[i].getName());
}
By default:
join
is a column-wise left join
pd.merge
is a column-wise inner join
pd.concat
is a row-wise outer join
pd.concat
:
takes Iterable arguments. Thus, it cannot take DataFrames directly (use [df,df2]
)
Dimensions of DataFrame should match along axis
Join
and pd.merge
:
can take DataFrame arguments
You can use Comparator.reverseOrder()
to have a comparator giving the reverse of the natural ordering.
If you want to reverse the ordering of an existing comparator, you can use Comparator.reversed()
.
Sample code:
Stream.of(1, 4, 2, 5)
.sorted(Comparator.reverseOrder());
// stream is now [5, 4, 2, 1]
Stream.of("foo", "test", "a")
.sorted(Comparator.comparingInt(String::length).reversed());
// stream is now [test, foo, a], sorted by descending length
yeah, the code like this work fine
<div>
<img>
</div>
but just to remind u, the style for image
object-fit : *depend on u*
so the final code be like Example
<div style="border: 1px solid red;">
<img
src="./assets/images/truck-toy.jpg"
alt=""
srcset=""
style="
border-radius: 50%;
height: 7.5rem;
width: 7.5rem;
object-fit: contain;"
/>
</div>
This may be a sketchy solution, and I'd appreciate anybody pointing out whether this is a bad idea, since it's not a standard use of functions. I've had some success getting HTML out of a PHP function without building the return value as a string with the following:
function noStrings() {
echo ''?>
<div>[Whatever HTML you want]</div>
<?php;
}
The just 'call' the function:
noStrings();
And it will output:
<div>[Whatever HTML you want]</div>
Using this method, you can also define PHP variables within the function and echo them out inside the HTML.
There is another consistent way (only for IE9+) in vanilla JavaScript for this:
const iframe = document.getElementById('iframe');
const handleLoad = () => console.log('loaded');
iframe.addEventListener('load', handleLoad, true)
And if you're interested in Observables this does the trick:
return Observable.fromEventPattern(
handler => iframe.addEventListener('load', handler, true),
handler => iframe.removeEventListener('load', handler)
);
I usually use these utility functions. element
is the HTML element and duration
is the desired duration in milliseconds.
export const fadeIn = (element, duration) => {
(function increment(value = 0) {
element.style.opacity = String(value);
if (element.style.opacity !== '1') {
setTimeout(() => {
increment(value + 0.1);
}, duration / 10);
}
})();
};
export const fadeOut = (element, duration) => {
(function decrement() {
(element.style.opacity -= 0.1) < 0 ? element.style.display = 'none' : setTimeout(() => {
decrement();
}, duration / 10);
})();
};
ModHeader extension for Google Chrome, is also a good option. You can just set the Headers you want and just enter the URL in the browser, it will automatically take the headers from the extension when you hit the url. Only thing is, it will send headers for each and every URL you will hit so you have to disable or delete it after use.
If you can create a string xml you can easily transform it to the xml document object e.g. -
String xmlString = "<?xml version=\"1.0\" encoding=\"utf-8\"?><a><b></b><c></c></a>";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(xmlString)));
} catch (Exception e) {
e.printStackTrace();
}
You can use the document object and xml parsing libraries or xpath to get back the ip address.
You also need to have 'Private Browsing' turned OFF.
Settings > Safari > Private Browsing > OFF
You have the wrong table set on the command. You should use the following on your setup:
ALTER TABLE scode_tracker.ap_visits ENGINE=MyISAM;
You can use the rc shell.
First install the package (it's less than 1 MB).
This an example of how you would discard standard output and pipe standard error to grep in rc
:
find /proc/ >[1] /dev/null |[2] grep task
You can do it without leaving Bash:
rc -c 'find /proc/ >[1] /dev/null |[2] grep task'
As you may have noticed, you can specify which file descriptor you want piped by using brackets after the pipe.
Standard file descriptors are numerated as such:
You can get textbox value and Id by the following simple example in dotNet programming
<html>
<head>
<script type="text/javascript">
function GetTextboxId_Value(textBox)
{
alert(textBox.value); // To get Text Box Value(Text)
alert(textBox.id); // To get Text Box Id like txtSearch
}
</script>
</head>
<body>
<input id="txtSearch" type="text" onkeyup="GetTextboxId_Value(this)" /> </body>
</html>
Evidently you can use Arrays.fill(), The way you have it done also works though.
I'm a fan of the Find-In-Files dialog in Notepad++. Bonus: It's free.
Here is how I do a Subview on iOS in Swift -
class CustomSubview : UIView {
init() {
super.init(frame: UIScreen.mainScreen().bounds);
let windowHeight : CGFloat = 150;
let windowWidth : CGFloat = 360;
self.backgroundColor = UIColor.whiteColor();
self.frame = CGRectMake(0, 0, windowWidth, windowHeight);
self.center = CGPoint(x: UIScreen.mainScreen().bounds.width/2, y: 375);
//for debug validation
self.backgroundColor = UIColor.grayColor();
print("My Custom Init");
return;
}
required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented"); }
}
Replace
f = open(D\\python\\HW\\2_1 - Copy.cp,"r");
by
f = open("D:\\python\\HW\\2_1 - Copy.cp", "r")
What tutorial are you using?
Try this one,
var timestamp = firebase.firestore.FieldValue.serverTimestamp()
var timestamp2 = new Date(timestamp.toDate()).toUTCString()
As Brian said:
According to a post on xda-developers, you can enable ADB over WiFi from the device with the commands
setprop service.adb.tcp.port 5555
stop adbd
start adbd
And you can disable it and return ADB to listening on USB with
setprop service.adb.tcp.port -1
stop adbd
start adbd
If you have USB access already, it is even easier to switch to using WiFi. From a command line on the computer that has the device connected via USB, issue the commands
adb tcpip 5555
adb connect 192.168.0.101:5555
To tell the ADB daemon return to listening over USB
adb usb
There are also several apps on the Android Market that automate this process.
It works.You just need to access the android shell and type those commands...
One other (easier) solution is on the Market: adbWireless, it will automatically set your phone.
Root is required! for both...
Use JSON lib E.g. http://www.json.org/java/
// Assume you have a Map<String, String> in JSONObject jdata
@SuppressWarnings("unchecked")
Iterator<String> nameItr = jdata.keys();
Map<String, String> outMap = new HashMap<String, String>();
while(nameItr.hasNext()) {
String name = nameItr.next();
outMap.put(name, jdata.getString(name));
}
Check out SQLCMD command line tool that comes with SQL Server. http://technet.microsoft.com/en-us/library/ms162773.aspx
This works for me for MS SQL server:
select * from test
where
year(date) = 2015
and month(date) = 10
and day(date)= 28 ;
You can declare trk by the following ways : - either
trk : [{
lat : String,
lng : String
}]
or
trk : { type : Array , "default" : [] }
In the second case during insertion make the object and push it into the array like
db.update({'Searching criteria goes here'},
{
$push : {
trk : {
"lat": 50.3293714,
"lng": 6.9389939
} //inserted data is the object to be inserted
}
});
or you can set the Array of object by
db.update ({'seraching criteria goes here ' },
{
$set : {
trk : [ {
"lat": 50.3293714,
"lng": 6.9389939
},
{
"lat": 50.3293284,
"lng": 6.9389634
}
]//'inserted Array containing the list of object'
}
});
Yes, ensure
is called in any circumstances. For more information see "Exceptions, Catch, and Throw" of the Programming Ruby book and search for "ensure".
To specify a directory to search for (binary) libraries, you just use -L
:
-L/data[...]/lib
To specify the actual library name, you use -l
:
-lfoo # (links libfoo.a or libfoo.so)
To specify a directory to search for include files (different from libraries!) you use -I
:
-I/data[...]/lib
So I think what you want is something like
g++ -g -Wall -I/data[...]/lib testing.cpp fileparameters.cpp main.cpp -o test
These compiler flags (amongst others) can also be found at the GNU GCC Command Options manual:
Since no answer stated this:
Make sure that, if you are using a virtual environment, you have activated it before trying to run the program.
If you don't really know if you are using a virtual environment or not, check with the other contributors of the project. Or maybe try to find a file with the name activate
like this: find . -name activate
.
I have got the same issue, here I give my problem and my solution hoping this would help someone:
Following other people recommendation I went to the log of the server (Windows Server 2012 in my case) in :
Control Panel -> Administrative Tools -> Event Viewer
Then in the left side:
Windows Logs -> Application:
In the warnings I found the message from my site and in my case it was due to a null reference:
*Exception type: NullReferenceException
Exception message: Object reference not set to an instance of an object.*
And checking at the function described in the log I found a non initialized object and that was it.
So it could be a null reference exception in the code. Hope someone find this useful, greetings.
New, detailed answer and explanation to an old, frequently asked question...
Short answer: If you don't add elementFormDefault="qualified"
to xsd:schema
, then the default unqualified
value means that locally declared elements are in no namespace.
There's a lot of confusion regarding what elementFormDefault
does, but this can be quickly clarified with a short example...
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
xmlns:target="http://www.levijackson.net/web340/ns"
targetNamespace="http://www.levijackson.net/web340/ns">
<element name="assignments">
<complexType>
<sequence>
<element name="assignment" type="target:assignmentInfo"
minOccurs="1" maxOccurs="unbounded"/>
</sequence>
</complexType>
</element>
<complexType name="assignmentInfo">
<sequence>
<element name="name" type="string"/>
</sequence>
<attribute name="id" type="string" use="required"/>
</complexType>
</schema>
Key points:
assignment
element is locally defined.elementFormDefault
is unqualified
.elementFormDefault="qualified"
so that assignment
is in the target namespace as one would
expect.form
attribute on xs:element
declarations for which elementFormDefault
establishes default values.This XML looks like it should be valid according to the above XSD:
<assignments xmlns="http://www.levijackson.net/web340/ns"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.levijackson.net/web340/ns try.xsd">
<assignment id="a1">
<name>John</name>
</assignment>
</assignments>
Notice:
assignments
places assignments
and all of its descendents in the default namespace (http://www.levijackson.net/web340/ns
).Despite looking valid, the above XML yields the following confusing validation error:
[Error] try.xml:4:23: cvc-complex-type.2.4.a: Invalid content was found starting with element 'assignment'. One of '{assignment}' is expected.
Notes:
assignment
element but it actually found an assignment
element. (WTF){
and }
around assignment
means that validation was expecting assignment
in no namespace here. Unfortunately, when it says that it found an assignment
element, it doesn't mention that it found it in a default namespace which differs from no namespace.elementFormDefault="qualified"
to the xsd:schema
element of the XSD. This means valid XML must place elements in the target namespace when locally declared in the XSD; otherwise, valid XML must place locally declared elements in no namespace.assignment
be in no namespace. This can be achieved,
for example, by adding xmlns=""
to the assignment
element.Credits: Thanks to Michael Kay for helpful feedback on this answer.
You can use the JDOM library in Java. Define your tags as Element objects, document your elements with Document Class, and build your xml file with SAXBuilder. Try this example:
//Root Element
Element root=new Element("CONFIGURATION");
Document doc=new Document();
//Element 1
Element child1=new Element("BROWSER");
//Element 1 Content
child1.addContent("chrome");
//Element 2
Element child2=new Element("BASE");
//Element 2 Content
child2.addContent("http:fut");
//Element 3
Element child3=new Element("EMPLOYEE");
//Element 3 --> In this case this element has another element with Content
child3.addContent(new Element("EMP_NAME").addContent("Anhorn, Irene"));
//Add it in the root Element
root.addContent(child1);
root.addContent(child2);
root.addContent(child3);
//Define root element like root
doc.setRootElement(root);
//Create the XML
XMLOutputter outter=new XMLOutputter();
outter.setFormat(Format.getPrettyFormat());
outter.output(doc, new FileWriter(new File("myxml.xml")));
The lack of an exponential operator for C# was a big annoyance for us when looking for a new language to convert our calculation software to from the good ol' vb6.
I'm glad we went with C# but it still annoys me whenever I'm writing a complex equation including exponents. The Math.Pow()
method makes equations quite hard to read IMO.
Our solution was to create a special DoubleX
class where we override the ^
-operator (see below)
This works fairly well as long as you declare at least one of the variables as DoubleX
:
DoubleX a = 2;
DoubleX b = 3;
Console.WriteLine($"a = {a}, b = {b}, a^b = {a ^ b}");
or use an explicit converter on standard doubles:
double c = 2;
double d = 3;
Console.WriteLine($"c = {c}, d = {d}, c^d = {c ^ (DoubleX)d}"); // Need explicit converter
One problem with this method though is that the exponent is calculated in the wrong order compared to other operators. This can be avoided by always putting an extra (
)
around the operation which again makes it a bit harder to read the equations:
DoubleX a = 2;
DoubleX b = 3;
Console.WriteLine($"a = {a}, b = {b}, 3+a^b = {3 + a ^ b}"); // Wrong result
Console.WriteLine($"a = {a}, b = {b}, 3+a^b = {3 + (a ^ b)}"); // Correct result
I hope this can be of help to others who uses a lot of complex equations in their code, and maybe someone even has an idea of how to improve this method?!
DoubleX
class:
using System;
namespace ExponentialOperator
{
/// <summary>
/// Double class that uses ^ as exponential operator
/// </summary>
public class DoubleX
{
#region ---------------- Fields ----------------
private readonly double _value;
#endregion ------------- Fields ----------------
#region -------------- Properties --------------
public double Value
{
get { return _value; }
}
#endregion ----------- Properties --------------
#region ------------- Constructors -------------
public DoubleX(double value)
{
_value = value;
}
public DoubleX(int value)
{
_value = Convert.ToDouble(value);
}
#endregion ---------- Constructors -------------
#region --------------- Methods ----------------
public override string ToString()
{
return _value.ToString();
}
#endregion ------------ Methods ----------------
#region -------------- Operators ---------------
// Change the ^ operator to be used for exponents.
public static DoubleX operator ^(DoubleX value, DoubleX exponent)
{
return Math.Pow(value, exponent);
}
public static DoubleX operator ^(DoubleX value, double exponent)
{
return Math.Pow(value, exponent);
}
public static DoubleX operator ^(double value, DoubleX exponent)
{
return Math.Pow(value, exponent);
}
public static DoubleX operator ^(DoubleX value, int exponent)
{
return Math.Pow(value, exponent);
}
#endregion ----------- Operators ---------------
#region -------------- Converters --------------
// Allow implicit convertion
public static implicit operator DoubleX(double value)
{
return new DoubleX(value);
}
public static implicit operator DoubleX(int value)
{
return new DoubleX(value);
}
public static implicit operator Double(DoubleX value)
{
return value._value;
}
#endregion ----------- Converters --------------
}
}
I had a similar error, but in my case the cause was file renaming. I was creating a gzipped file file1.tar.gz
and repeatedly updating it in another tarfile with tar -uvf ./combined.tar ./file1.tar.gz
. I got the unexpected EOF error when after untarring combined.tar
and trying to untar file1.tar.gz
.
I noticed there was a difference in the output of file
before and after tarring:
$file file1.tar.gz
file1.tar.gz: gzip compressed data, was "file1.tar", last modified: Mon Jul 29 12:00:00 2019, from Unix
$tar xvf combined.tar
$file file1.tar.gz
file1.tar.gz: gzip compressed data, was "file_old.tar", last modified: Mon Jul 29 12:00:00 2019, from Unix
So, it appears that the file had a different name when I originally created combined.tar
, and using the tar update function doesn't overwrite the metadata for the gzipped filename. The solution was to recreate combined.tar
from scratch instead of updating it.
I still don't know exactly what happened, since changing the name of a gzipped file doesn't normally break it.
You can check if jQuery is loaded or not by many ways such as:
if (typeof jQuery == 'undefined') {
// jQuery IS NOT loaded, do stuff here.
}
if (typeof jQuery == 'function')
//or
if (typeof $== 'function')
if (jQuery) {
// This will throw an error in STRICT MODE if jQuery is not loaded, so don't use if using strict mode
alert("jquery is loaded");
} else {
alert("Not loaded");
}
if( 'jQuery' in window ) {
// Do Stuff
}
Now after checking if jQuery is not loaded, you can load jQuery like this:
Although this part has been answered by many in this post but still answering for the sake of completeness of the code
// This part should be inside your IF condition when you do not find jQuery loaded
var script = document.createElement('script');
script.type = "text/javascript";
script.src = "http://code.jquery.com/jquery-3.3.1.min.js";
document.getElementsByTagName('head')[0].appendChild(script);
If you are using a Form Control
, you can get the same property as ActiveX
by using OLEFormat.Object
property of the Shape Object
. Better yet assign it in a variable declared as OptionButton to get the Intellisense kick in.
Dim opt As OptionButton
With Sheets("Sheet1") ' Try to be always explicit
Set opt = .Shapes("Option Button 1").OLEFormat.Object ' Form Control
Debug.Pring opt.Value ' returns 1 (true) or -4146 (false)
End With
But then again, you really don't need to know the value.
If you use Form Control
, you associate a Macro
or sub routine with it which is executed when it is selected. So you just need to set up a sub routine that identifies which button is clicked and then execute a corresponding action for it.
For example you have 2 Form Control
Option Buttons.
Sub CheckOptions()
Select Case Application.Caller
Case "Option Button 1"
' Action for option button 1
Case "Option Button 2"
' Action for option button 2
End Select
End Sub
In above code, you have only one sub routine assigned to both option buttons.
Then you test which called the sub routine by checking Application.Caller
.
This way, no need to check whether the option button value is true or false.
Reading your comments took me to a dirty fix. This is not a right way, I know, but can be a work around.
$(function() {
$( "#inputFieldId" ).autocomplete({
source: function( event, ui ) {
alert("do your functions here");
return false;
}
});
});
Making use of CSS sprites and data uri gives extra interesting benefits like fast loading and less requests AND we get IE8 support by using image/base64:
HTML
<div class="div1"></div>
<div class="div2"></div>
CSS
.div1:after, .div2:after {
content: '';
display: block;
height: 80px;
width: 80px;
background-image: url(data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20version%3D%221.1%22%20height%3D%2280%22%20width%3D%22160%22%3E%0D%0A%20%20%3Ccircle%20cx%3D%2240%22%20cy%3D%2240%22%20r%3D%2238%22%20stroke%3D%22black%22%20stroke-width%3D%221%22%20fill%3D%22red%22%20%2F%3E%0D%0A%20%20%3Ccircle%20cx%3D%22120%22%20cy%3D%2240%22%20r%3D%2238%22%20stroke%3D%22black%22%20stroke-width%3D%221%22%20fill%3D%22blue%22%20%2F%3E%0D%0A%3C%2Fsvg%3E);
}
.div2:after {
background-position: -80px 0;
}
For IE8, change to this:
background-image: url(data:image/png;base64,data......);
You have an error in you script tag construction, this:
<script language="JavaScript" type="text/javascript" script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js"></script>
Should look like this:
<script language="JavaScript" type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js"></script>
You have a 'script' word lost in the middle of your script tag. Also you should remove the http:// to let the browser decide whether to use HTTP or HTTPS.
UPDATE
But your main error is that you are including jQuery UI (ONLY) you must include jQuery first! jQuery UI and jQuery are used together, not in separate. jQuery UI depends on jQuery. You should put this line before jQuery UI:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
If order does not matter and when it's more performant to run in parallel, Collect to a Map and then get values:
employee.stream().collect(Collectors.toConcurrentMap(Employee::getId, Function.identity(), (p, q) -> p)).values()
1.Monolithic Kernel (Pure Monolithic) :all
All Kernel Services From single component
(-) addition/removal is not possible, less/Zero flexible
(+) inter Component Communication is better
e.g. :- Traditional Unix
2.Micro Kernel :few
few services(Memory management ,CPU management,IPC etc) from core kernel, other services(File management,I/O management. etc.) from different layers/component
Split Approach [Some services is in privileged(kernel) mode and some are in Normal(user) mode]
(+)flexible for changes/up-gradations
(-)communication overhead
e.g.:- QNX etc.
3.Modular kernel(Modular Monolithic) :most
Combination of Micro and Monolithic kernel
Collection of Modules -- modules can be --> Static + Dynamic
Drivers come in the form of Modules
e.g. :- Linux Modern OS
Correct Syntax: select spelling was wrong
INSERT INTO courses (name, location, gid)
SELECT name, location, 'whatever you want'
FROM courses
WHERE cid = $ci
img {_x000D_
max-width: 80px; /* Also works with percentage value like 100% */_x000D_
height: auto;_x000D_
}
_x000D_
<p>This image is originally 400x400 pixels, but should get resized by the CSS:</p>_x000D_
<img width="400" height="400" src="https://i.stack.imgur.com/aEEkn.png">_x000D_
_x000D_
<p>Let's say the author of the HTML deliberately wants_x000D_
the height to be half the value of the width,_x000D_
this CSS will ignore the HTML author's wishes, which may or may not be what you want:_x000D_
</p>_x000D_
<img width="400" height="200" src="https://i.stack.imgur.com/aEEkn.png">
_x000D_
Command EXPOSE
in your Dockerfile lets you bind container's port to some port on the host machine but it doesn't do anything else.
When running container, to bind ports specify -p
option.
So let's say you expose port 5000. After building the image when you run the container, run docker run -p 5000:5000 name
. This binds container's port 5000 to your laptop/computers port 5000 and that portforwarding lets container to receive outside requests.
This should do it.
You can try my function for merging images horizontally or vertically without changing image ratio. just copy paste will work.
function merge($filename_x, $filename_y, $filename_result, $mergeType = 0) {
//$mergeType 0 for horizandal merge 1 for vertical merge
// Get dimensions for specified images
list($width_x, $height_x) = getimagesize($filename_x);
list($width_y, $height_y) = getimagesize($filename_y);
$lowerFileName = strtolower($filename_x);
if(substr_count($lowerFileName, '.jpg')>0 || substr_count($lowerFileName, '.jpeg')>0){
$image_x = imagecreatefromjpeg($filename_x);
}else if(substr_count($lowerFileName, '.png')>0){
$image_x = imagecreatefrompng($filename_x);
}else if(substr_count($lowerFileName, '.gif')>0){
$image_x = imagecreatefromgif($filename_x);
}
$lowerFileName = strtolower($filename_y);
if(substr_count($lowerFileName, '.jpg')>0 || substr_count($lowerFileName, '.jpeg')>0){
$image_y = imagecreatefromjpeg($filename_y);
}else if(substr_count($lowerFileName, '.png')>0){
$image_y = imagecreatefrompng($filename_y);
}else if(substr_count($lowerFileName, '.gif')>0){
$image_y = imagecreatefromgif($filename_y);
}
if($mergeType==0){
//for horizandal merge
if($height_y<$height_x){
$new_height = $height_y;
$new_x_height = $new_height;
$precentageReduced = ($height_x - $new_height)/($height_x/100);
$new_x_width = ceil($width_x - (($width_x/100) * $precentageReduced));
$tmp = imagecreatetruecolor($new_x_width, $new_x_height);
imagecopyresampled($tmp, $image_x, 0, 0, 0, 0, $new_x_width, $new_x_height, $width_x, $height_x);
$image_x = $tmp;
$height_x = $new_x_height;
$width_x = $new_x_width;
}else{
$new_height = $height_x;
$new_y_height = $new_height;
$precentageReduced = ($height_y - $new_height)/($height_y/100);
$new_y_width = ceil($width_y - (($width_y/100) * $precentageReduced));
$tmp = imagecreatetruecolor($new_y_width, $new_y_height);
imagecopyresampled($tmp, $image_y, 0, 0, 0, 0, $new_y_width, $new_y_height, $width_y, $height_y);
$image_y = $tmp;
$height_y = $new_y_height;
$width_y = $new_y_width;
}
$new_width = $width_x + $width_y;
$image = imagecreatetruecolor($new_width, $new_height);
imagecopy($image, $image_x, 0, 0, 0, 0, $width_x, $height_x);
imagecopy($image, $image_y, $width_x, 0, 0, 0, $width_y, $height_y);
}else{
//for verical merge
if($width_y<$width_x){
$new_width = $width_y;
$new_x_width = $new_width;
$precentageReduced = ($width_x - $new_width)/($width_x/100);
$new_x_height = ceil($height_x - (($height_x/100) * $precentageReduced));
$tmp = imagecreatetruecolor($new_x_width, $new_x_height);
imagecopyresampled($tmp, $image_x, 0, 0, 0, 0, $new_x_width, $new_x_height, $width_x, $height_x);
$image_x = $tmp;
$width_x = $new_x_width;
$height_x = $new_x_height;
}else{
$new_width = $width_x;
$new_y_width = $new_width;
$precentageReduced = ($width_y - $new_width)/($width_y/100);
$new_y_height = ceil($height_y - (($height_y/100) * $precentageReduced));
$tmp = imagecreatetruecolor($new_y_width, $new_y_height);
imagecopyresampled($tmp, $image_y, 0, 0, 0, 0, $new_y_width, $new_y_height, $width_y, $height_y);
$image_y = $tmp;
$width_y = $new_y_width;
$height_y = $new_y_height;
}
$new_height = $height_x + $height_y;
$image = imagecreatetruecolor($new_width, $new_height);
imagecopy($image, $image_x, 0, 0, 0, 0, $width_x, $height_x);
imagecopy($image, $image_y, 0, $height_x, 0, 0, $width_y, $height_y);
}
$lowerFileName = strtolower($filename_result);
if(substr_count($lowerFileName, '.jpg')>0 || substr_count($lowerFileName, '.jpeg')>0){
imagejpeg($image, $filename_result);
}else if(substr_count($lowerFileName, '.png')>0){
imagepng($image, $filename_result);
}else if(substr_count($lowerFileName, '.gif')>0){
imagegif($image, $filename_result);
}
// Clean up
imagedestroy($image);
imagedestroy($image_x);
imagedestroy($image_y);
}
merge('images/h_large.jpg', 'images/v_large.jpg', 'images/merged_har.jpg',0); //merge horizontally
merge('images/h_large.jpg', 'images/v_large.jpg', 'images/merged.jpg',1); //merge vertically
This can also be done in CSS, for more customisability:
.hoverable {
position: relative;
}
.hoverable>.hoverable__tooltip {
display: none;
}
.hoverable:hover>.hoverable__tooltip {
display: inline;
position: absolute;
top: 1em;
left: 1em;
background: #888;
border: 1px solid black;
}
_x000D_
<div class="hoverable">
<span class="hoverable__main">Main text</span>
<span class="hoverable__tooltip">Hover text</span>
</div>
_x000D_
(Obviously, styling can be improved)
Just set
webView.mediaPlaybackRequiresUserAction = NO;
The autoplay works for me on iOS.
This example puts your JSON into proper format and does an existence check. I use jquery for convenience.
<!-- HTML -->
<span id="test">Hello</span><br>
<span id="test2">Hello</span>
//Javascript
$(document).ready(function(){
var JSON = {"animals":[{"name":"cat"}, {"name":"dog"}]};
if(JSON.animals[1].name){
$("#test").html("It exists");
}
if(!JSON.animals[2]){
$("#test2").html("It doesn't exist");
}
});
Try using os.system
:
os.system("script2.py 1")
execfile
is different because it is designed to run a sequence of Python statements in the current execution context. That's why sys.argv
didn't change for you.
Attributes in JSP tag libraries in general can be either static or resolved at request time. If they are resolved at request time the JSP will resolve their value at runtime and pass the output on to the tag. This means you can put pretty much any JSP code into the attribute and the tag will behave accordingly to what output that produces.
If you look at the jstl taglib docs you can see which attributes are reuest time and which are not. http://java.sun.com/products/jsp/jstl/1.1/docs/tlddocs/index.html
You seem to have misunderstood how character classes definition works in regex.
To match any of the strings 01
, 02
, 03
, 04
, 05
, 06
, 07
, 08
, 09
, 10
, 11
, or 12
, something like this works:
0[1-9]|1[0-2]
A character class, by itself, attempts to match one and exactly one character from the input string. [01-12]
actually defines [012]
, a character class that matches one character from the input against any of the 3 characters 0
, 1
, or 2
.
The -
range definition goes from 1
to 1
, which includes just 1
. On the other hand, something like [1-9]
includes 1
, 2
, 3
, 4
, 5
, 6
, 7
, 8
, 9
.
Beginners often make the mistakes of defining things like [this|that]
. This doesn't "work". This character definition defines [this|a]
, i.e. it matches one character from the input against any of 6 characters in t
, h
, i
, s
, |
or a
. More than likely (this|that)
is what is intended.
So it's obvious now that a pattern like between [24-48] hours
doesn't "work". The character class in this case is equivalent to [248]
.
That is, -
in a character class definition doesn't define numeric range in the pattern. Regex engines doesn't really "understand" numbers in the pattern, with the exception of finite repetition syntax (e.g. a{3,5}
matches between 3 and 5 a
).
Range definition instead uses ASCII/Unicode encoding of the characters to define ranges. The character 0
is encoded in ASCII as decimal 48; 9
is 57. Thus, the character definition [0-9]
includes all character whose values are between decimal 48 and 57 in the encoding. Rather sensibly, by design these are the characters 0
, 1
, ..., 9
.
Let's take a look at another common character class definition [a-zA-Z]
In ASCII:
A
= 65, Z
= 90a
= 97, z
= 122This means that:
[a-zA-Z]
and [A-Za-z]
are equivalent[a-Z]
is likely to be an illegal character range
a
(97) is "greater than" than Z
(90)[A-z]
is legal, but also includes these six characters:
[
(91), \
(92), ]
(93), ^
(94), _
(95), `
(96)I developed a jQuery plugin that allows you to call any core PHP function or even user defined PHP functions as methods of the plugin: jquery.php
After including jquery and jquery.php in the head of our document and placing request_handler.php on our server we would start using the plugin in the manner described below.
For ease of use reference the function in a simple manner:
var P = $.fn.php;
Then initialize the plugin:
P('init',
{
// The path to our function request handler is absolutely required
'path': 'http://www.YourDomain.com/jqueryphp/request_handler.php',
// Synchronous requests are required for method chaining functionality
'async': false,
// List any user defined functions in the manner prescribed here
// There must be user defined functions with these same names in your PHP
'userFunctions': {
languageFunctions: 'someFunc1 someFunc2'
}
});
And now some usage scenarios:
// Suspend callback mode so we don't work with the DOM
P.callback(false);
// Both .end() and .data return data to variables
var strLenA = P.strlen('some string').end();
var strLenB = P.strlen('another string').end();
var totalStrLen = strLenA + strLenB;
console.log( totalStrLen ); // 25
// .data Returns data in an array
var data1 = P.crypt("Some Crypt String").data();
console.log( data1 ); // ["$1$Tk1b01rk$shTKSqDslatUSRV3WdlnI/"]
Demonstrating PHP function chaining:
var data1 = P.strtoupper("u,p,p,e,r,c,a,s,e").strstr([], "C,A,S,E").explode(",", [], 2).data();
var data2 = P.strtoupper("u,p,p,e,r,c,a,s,e").strstr([], "C,A,S,E").explode(",", [], 2).end();
console.log( data1, data2 );
Demonstrating sending a JSON block of PHP pseudo-code:
var data1 =
P.block({
$str: "Let's use PHP's file_get_contents()!",
$opts:
[
{
http: {
method: "GET",
header: "Accept-language: en\r\n" +
"Cookie: foo=bar\r\n"
}
}
],
$context:
{
stream_context_create: ['$opts']
},
$contents:
{
file_get_contents: ['http://www.github.com/', false, '$context']
},
$html:
{
htmlentities: ['$contents']
}
}).data();
console.log( data1 );
The backend configuration provides a whitelist so you can restrict which functions can be called. There are a few other patterns for working with PHP described by the plugin as well.
For new projects, I've started having every class I write extend the same base class where I can put all the utility methods that are annoyingly missing from Java like this one, the equivalent for collections (tired of writing list != null && ! list.isEmpty()), null-safe equals, etc. I still use Apache Commons for the implementation but this saves a small amount of typing and I haven't seen any negative effects.
I had the same requirement - I just use this. User enters the number of days by which he/she wants to limit the calendar range to.
SELECT DAY, offset
FROM (SELECT to_char(SYSDATE, 'DD-MON-YYYY') AS DAY, 0 AS offset
FROM DUAL
UNION ALL
SELECT to_char(SYSDATE - rownum, 'DD-MON-YYYY'), rownum
FROM all_objects d)
where offset <= &No_of_days
I use the above result set as driving view in LEFT OUTER JOIN
with other views involving tables which have dates.
This answer is equivalent to some of the existing answers, but ECMAScript 6 arrow functions provide a much more compact syntax that allows us to define an inline sort function without sacrificing readability:
numArray = numArray.sort((a, b) => a - b);
It is supported in most browsers today.
You get the cursor position by calling GetCursorPos
.
POINT p;
if (GetCursorPos(&p))
{
//cursor position now in p.x and p.y
}
This returns the cursor position relative to screen coordinates. Call ScreenToClient
to map to window coordinates.
if (ScreenToClient(hwnd, &p))
{
//p.x and p.y are now relative to hwnd's client area
}
You hide and show the cursor with ShowCursor
.
ShowCursor(FALSE);//hides the cursor
ShowCursor(TRUE);//shows it again
You must ensure that every call to hide the cursor is matched by one that shows it again.
If you are using eloquent model (by looking at your code, i think you are), you dont need to convert it into array. Just use it as object. Becaus elike Thomas Kim said, by default it is a Carbon instance
So it should be
$suborder['payment_date'] = $item->created_at->format('Y-m-d')
But if it is not then, you need convert it to Carbon object as Milan Maharjan answer
$createdAt = Carbon::parse($item['created_at']);
My Scenario
def example():
cl = [0, 1]
def inner():
#cl = [1, 2] # access this way will throw `reference before assignment`
cl[0] = 1
cl[1] = 2 # these won't
inner()
There is no difference.
COUNT(1)
is basically just counting a constant value 1 column for each row. As other users here have said, it's the same as COUNT(0)
or COUNT(42)
. Any non-NULL
value will suffice.
http://asktom.oracle.com/pls/asktom/f?p=100:11:2603224624843292::::P11_QUESTION_ID:1156151916789
The Oracle optimizer did apparently use to have bugs in it, which caused the count to be affected by which column you picked and whether it was in an index, so the COUNT(1) convention came into being.
youtube/embed, two flavors:
https://www.youtube.com/embed/watch?v=eAxV4uO8oTU&list=RDeAxV4uO8oTU&start_radio=1 https://www.youtube.com/embed/CNG7yrHHJ5A
paste in your browser and see
the original:
https://www.youtube.com/watch?v=eAxV4uO8oTU&list=RDeAxV4uO8oTU&start_radio=1 https://www.youtube.com/watch?v=CNG7yrHHJ5A
one needs to keep "watch?V=", the other not
Html Code :
<a id="f">Show First content!</a>
<br/>
<a id="s">Show Second content!!</a>
<div class="a">Default Content</div>
<div class="ab hideDiv">First content</div>
<div class="abc hideDiv">Second content</div>
Script code:
$(document).ready(function() {
$("#f").mouseover(function(){
$('.a,.abc').addClass('hideDiv');
$('.ab').removeClass('hideDiv');
}).mouseout(function() {
$('.a').removeClass('hideDiv');
$('.ab,.abc').addClass('hideDiv');
});
$("#s").mouseover(function(){
$('.a,.ab').addClass('hideDiv');
$('.abc').removeClass('hideDiv');
}).mouseout(function() {
$('.a').removeClass('hideDiv');
$('.ab,.abc').addClass('hideDiv');
});
});
css code:
.hideDiv
{
display:none;
}
form
If the name attribute is specified, the form controller is published onto the current scope under this name.
Alias: ngForm
In Angular, forms can be nested. This means that the outer form is valid when all of the child forms are valid as well. However, browsers do not allow nesting of elements, so Angular provides the ngForm directive which behaves identically to but can be nested. This allows you to have nested forms, which is very useful when using Angular validation directives in forms that are dynamically generated using the ngRepeat directive. Since you cannot dynamically generate the name attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an ngForm directive and nest these in an outer form element.
CSS classes
ng-valid is set if the form is valid.
ng-invalid is set if the form is invalid.
ng-pristine is set if the form is pristine.
ng-dirty is set if the form is dirty.
ng-submitted is set if the form was submitted.
Keep in mind that ngAnimate can detect each of these classes when added and removed.
Submitting a form and preventing the default action
Since the role of forms in client-side Angular applications is different than in classical roundtrip apps, it is desirable for the browser not to translate the form submission into a full page reload that sends the data to the server. Instead some javascript logic should be triggered to handle the form submission in an application-specific way.
For this reason, Angular prevents the default action (form submission to the server) unless the element has an action attribute specified.
You can use one of the following two ways to specify what javascript method should be called when a form is submitted:
ngSubmit directive on the form element
ngClick directive on the first button or input field of type submit (input[type=submit])
To prevent double execution of the handler, use only one of the ngSubmit or ngClick directives.
This is because of the following form submission rules in the HTML specification:
If a form has only one input field then hitting enter in this field triggers form submit (ngSubmit)
if a form has 2+ input fields and no buttons or input[type=submit]
then hitting enter doesn't trigger submit
if a form has one or more input fields and one or more buttons or input[type=submit]
then hitting enter in any of the input fields will trigger the click handler on the first button or input[type=submit]
(ngClick) and a submit handler on the enclosing form (ngSubmit).
Any pending ngModelOptions changes will take place immediately when an enclosing form is submitted. Note that ngClick events will occur before the model is updated.
Use ngSubmit to have access to the updated model.
app.js:
angular.module('formExample', [])
.controller('FormController', ['$scope', function($scope) {
$scope.userType = 'guest';
}]);
Form:
<form name="myForm" ng-controller="FormController" class="my-form">
userType: <input name="input" ng-model="userType" required>
<span class="error" ng-show="myForm.input.$error.required">Required!</span>
userType = {{userType}}
myForm.input.$valid = {{myForm.input.$valid}}
myForm.input.$error = {{myForm.input.$error}}
myForm.$valid = {{myForm.$valid}}
myForm.$error.required = {{!!myForm.$error.required}}
</form>
Source: AngularJS: API: form
if (/^\s+$/.test(myString))
{
//string contains only whitespace
}
this checks for 1 or more whitespace characters, if you it to also match an empty string then replace +
with *
.
This is my solution
var cells = Array.prototype.slice.call(document.getElementById("tableI").getElementsByTagName("td"));
for(var i in cells){
console.log("My contents is \"" + cells[i].innerHTML + "\"");
}
(function(){_x000D_
_x000D_
var a= b = 3;_x000D_
var ed = 103;_x000D_
_x000D_
})();_x000D_
_x000D_
_x000D_
_x000D_
//console.log(ed); //ed is not defined_x000D_
_x000D_
console.log("a defined? " + (typeof a !== 'undefined')); //no define_x000D_
console.log("b defined? " + (typeof b !== 'undefined')); //yes define_x000D_
console.log(typeof(b)); //number_x000D_
console.log(typeof(4+7)); //number_x000D_
console.log(b); //3_x000D_
console.log(typeof("4"+"7")); //string_x000D_
var e= "ggg";_x000D_
console.log(typeof(e)); //string_x000D_
var ty=typeof(b);_x000D_
console.log(ty); //number_x000D_
console.log(typeof false); //boolean_x000D_
console.log(typeof 1); //number_x000D_
console.log(typeof 0); //number_x000D_
console.log(typeof true); //boolean_x000D_
_x000D_
_x000D_
console.log(typeof Math.tan); //function_x000D_
console.log(typeof function(){}); //function _x000D_
_x000D_
if(typeof neverDeclared == "undefined") //no errors_x000D_
if(typeof neverDeclared === "undefined") //no errors_x000D_
_x000D_
//if(neverDeclared == null) //showing error _x000D_
_x000D_
_x000D_
console.log(typeof {a:1}); //object_x000D_
console.log(typeof null); //object_x000D_
console.log(typeof JSON); //object_x000D_
console.log(typeof Math); //object_x000D_
console.log(typeof /a-z/); //object_x000D_
console.log(typeof new Date()); //object_x000D_
_x000D_
console.log(typeof afbc); //undefined_x000D_
//console.log(typeof new);//error_x000D_
_x000D_
document.write("<br> * oprator as math ");_x000D_
var r=14*"4";_x000D_
document.write(r);_x000D_
_x000D_
document.write("<br> + oprator as string ");_x000D_
var r=14+"44";_x000D_
document.write(r);_x000D_
_x000D_
document.write("<br> Minus Operator work as mathematic ");_x000D_
var r=64-"44";_x000D_
document.write(r);_x000D_
_x000D_
_x000D_
document.write("<br>");_x000D_
console.log(typeof(4*"7")); //returns number_x000D_
console.log(typeof(4+"7")); //returns string_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
Interview Question in JavaScript
_x000D_
File may be inside a directory, in that case specify the path:
import os
old_file = os.path.join("directory", "a.txt")
new_file = os.path.join("directory", "b.kml")
os.rename(old_file, new_file)
DPI should not be stored in an bitmap image file, as most sources of data for bitmaps render it meaningless.
A bitmap image is stored as pixels. Pixels have no inherent size in any respect. It's only at render time - be it monitor, printer, or automated crossstitching machine - that DPI matters.
A 800x1000 pixel bitmap image, printed at 100 dpi, turns into a nice 8x10" photo. Printed at 200 dpi, the EXACT SAME bitmap image turns into a 4x5" photo.
Capture an image with a digital camera, and what does DPI mean? It's certainly not the size of the area focused onto the CCD imager - that depends on the distance, and with NASA returning images of galaxies that are 100,000 light years across, and 2 million light years apart, in the same field of view, what kind of DPI do you get from THAT information?
Don't fall victim to the idea of the DPI of a bitmap image - it's a mistake. A bitmap image has no physical dimensions (save for a few micrometers of storage space in RAM or hard drive). It's only a displayed image, or a printed image, that has a physical size in inches, or millimeters, or furlongs.
Maybe it is very very bad way and just for lazy person but I decided to say it.
I used PHP and bootstrap and fontawsome too
for simple I have 2 pages: 1.index and 2.create-user
put this code above your code
<?php
$name=basename($_SERVER["REQUEST_URI"]);
$name=str_replace(".php","",$name);
switch ($name) {
case "create-user":
$a = 2;
break;
case "index":
$a = 1;
break;
default:
$a=1;
}
?>
and
in menu you add <?php if($a==1){echo "active";} ?>
in class for menu1
and for menu2 you add <?php if($a==2){echo "active";} ?>
<ul id="menu" class="navbar-nav flex-column text-right mt-3 p-1">
<li class="nav-item mb-2">
<a href="index.php" class="nav-link text-white customlihamid <?php if($a==1){echo "active";} ?>"><i
class="fas fa-home fa-lg text-light ml-3"></i>dashbord</a>
</li>
<li class="nav-item mb-2">
<a href="#" href="javascript:" data-parent="#menu" data-toggle="collapse"
class="accordion-toggle nav-link text-white customlihamid <?php if($a==2){echo "active";} ?>" data-target="#tickets">
<i class="fas fa-user fa-lg text-light ml-3"></i>manage users
<span class="float-left"><i class="fas fa-angle-down"></i></span>
</a>
<ul class="collapse list-unstyled mt-2 mr-1 pr-2" id="tickets">
<li class="nav-item mb-2">
<a href="create-user.php" class="nav-link text-white customlihamid"><i class="fas fa-user-plus fa-lg text-light ml-3"></i>add user</a>
</li>
<li class="nav-item mb-2">
<a href="#" class="nav-link text-white customlihamid"><i class="fas fa-user-times fa-lg text-light ml-3"></i>delete user</a>
</li>
</ul>
</li>
</ul>
and add in css
.customlihamid {
transition: all .4s;
}
.customlihamid:hover {
background-color: #8a8a8a;
border-radius: 5px;
color: #00cc99;
}
.nav-item > .nav-link.active {
background-color: #00cc99;
border-radius: 7px;
box-shadow: 5px 7px 10px #111;
transition: all .3s;
}
.nav-item > .nav-link.active:hover {
background-color: #8eccc1;
border-radius: 7px;
box-shadow: 5px 7px 20px #111;
transform: translateY(-1px);
}
and in js add
$(document).ready(function () {
$('.navbar-nav .nav-link').click(function(){
$('.navbar-nav .nav-link').removeClass('active');
$(this).addClass('active');
})
});
first check your work without js code to understand js code for what
If you declare the name for enumeration no error will occur.
If not declared, you have to use a typedef
:
enum enum_name {RANDOM, IMMEDIATE, SEARCH} strategy;
strategy = IMMEDIATE;
It will not display an error...
function areEqual(a, b){
let x = 0;
for (n in a){
if (a[n] == b[n]){x = 1;}
else {x = 0};
}
return x;
}
a = [1,2,3];
b = [1,2,3];
> console.log(areEqual(a,b))
true
I used it in this simple real code application
<script>_x000D_
let corrette = [1];_x000D_
let risposte = [];_x000D_
_x000D_
function areEqual(a, b){_x000D_
let x = 0;_x000D_
for (n in a){_x000D_
if (a[n] == b[n]){x = 1;}_x000D_
else {x = 0};_x000D_
}_x000D_
if (x){console.log("The 2 arrays are equal")}_x000D_
return x;_x000D_
}_x000D_
_x000D_
</script>_x000D_
_x000D_
Apporto di attrezzatura per cucina da parte del proprietario_x000D_
<button onclick="risposte[0]=1">Capitale proprio</button>_x000D_
<button onclick="risposte[0]=0">Capitale di debito</button>_x000D_
<button onclick="risposte[0]=0">Debito commerciale</button>_x000D_
_x000D_
<br><hr>_x000D_
<button onclick="if(areEqual(corrette,risposte)){controlla.innerHTML='Esatto'}else{controlla.innerHTML='No'}">Controlla le risposte</button>_x000D_
<div id="controlla"></div>
_x000D_
I created a PHP class for this with a corresponding jQuery plugin. I've open-sourced it at https://github.com/peterjtracey/timezoneWidget - the PHP code is inspired by another stackoverflow answer, but I think much more elegant. The jQuery plugin gives a great interface for selecting a timezone.
var gandalf = {
"real name": "Gandalf",
"age (est)": 11000,
"race": "Maia",
"haveRetirementPlan": true,
"aliases": [
"Greyhame",
"Stormcrow",
"Mithrandir",
"Gandalf the Grey",
"Gandalf the White"
]
};
//to console log object, we cannot use console.log("Object gandalf: " + gandalf);
console.log("Object gandalf: ");
//this will show object gandalf ONLY in Google Chrome NOT in IE
console.log(gandalf);
//this will show object gandalf IN ALL BROWSERS!
console.log(JSON.stringify(gandalf));
//this will show object gandalf IN ALL BROWSERS! with beautiful indent
console.log(JSON.stringify(gandalf, null, 4));
It's a little tricky because of the nested IFs but here is my answer (confirmed in Google Spreadsheets):
=IF(AND(A2>=0, A2<500), "Less than 500",
IF(AND(A2>=500, A2<1000), "Between 500 and 1000",
IF(AND(A2>=1000, A2<1500), "Between 1000 and 1500",
IF(AND(A2>=1500, A2<2000), "Between 1500 and 2000", "Undefined"))))
For me the solution was one of the methods had to be void, I had it as Boolean.
Another alternative that uses an external library is _.has() from Lodash.
E.g.
_.has(a, 'b.c')
is equal to
(a && a.b && a.b.c)
EDIT: As noted in the comments, you lose out on Typescript's type inference when using this method. E.g. Assuming that one's objects are properly typed, one would get a compilation error with (a && a.b && a.b.z) if z is not defined as a field of object b. But using _.has(a, 'b.z'), one would not get that error.
I wanted similar richness in colors for HTML elements, I was surprised to find that CSS now supports hsl() colors, so a full solution for me is below:
Also see How to automatically generate N "distinct" colors? for more alternatives more similar to this.
function colorByHashCode(value) {_x000D_
return "<span style='color:" + value.getHashCode().intToHSL() + "'>" + value + "</span>";_x000D_
}_x000D_
String.prototype.getHashCode = function() {_x000D_
var hash = 0;_x000D_
if (this.length == 0) return hash;_x000D_
for (var i = 0; i < this.length; i++) {_x000D_
hash = this.charCodeAt(i) + ((hash << 5) - hash);_x000D_
hash = hash & hash; // Convert to 32bit integer_x000D_
}_x000D_
return hash;_x000D_
};_x000D_
Number.prototype.intToHSL = function() {_x000D_
var shortened = this % 360;_x000D_
return "hsl(" + shortened + ",100%,30%)";_x000D_
};_x000D_
_x000D_
document.body.innerHTML = [_x000D_
"javascript",_x000D_
"is",_x000D_
"nice",_x000D_
].map(colorByHashCode).join("<br/>");
_x000D_
span {_x000D_
font-size: 50px;_x000D_
font-weight: 800;_x000D_
}
_x000D_
In HSL its Hue, Saturation, Lightness. So the hue between 0-359 will get all colors, saturation is how rich you want the color, 100% works for me. And Lightness determines the deepness, 50% is normal, 25% is dark colors, 75% is pastel. I have 30% because it fit with my color scheme best.
Cellpadding
is the amount of space between the outer edges of the
table cell and the content of the cell.
Cellspacing
is the amount of space in between the individual table cells.
More Details *Link 1*
After a lot of digging around I finally ended up downloading the source code of the recovery section of Android. Turns out you can actually send commands to the recovery.
* The arguments which may be supplied in the recovery.command file:
* --send_intent=anystring - write the text out to recovery.intent
* --update_package=path - verify install an OTA package file
* --wipe_data - erase user data (and cache), then reboot
* --wipe_cache - wipe cache (but not user data), then reboot
* --set_encrypted_filesystem=on|off - enables / diasables encrypted fs
Those are the commands you can use according to the one I found but that might be different for modded files. So using adb you can do this:
adb shell
recovery --wipe_data
Using --wipe_data seemed to do what I was looking for which was handy although I have not fully tested this as of yet.
EDIT:
For anyone still using this topic, these commands may change based on which recovery you are using. If you are using Clockword recovery, these commands should still work. You can find other commands in /cache/recovery/command
For more information please see here: https://github.com/CyanogenMod/android_bootable_recovery/blob/cm-10.2/recovery.c
To pass an object to a fragment, do the following:
First store the objects in Bundle, don't forget to put implements serializable in class.
CategoryRowFragment fragment = new CategoryRowFragment();
// pass arguments to fragment
Bundle bundle = new Bundle();
// event list we want to populate
bundle.putSerializable("eventsList", eventsList);
// the description of the row
bundle.putSerializable("categoryRow", categoryRow);
fragment.setArguments(bundle);
Then retrieve bundles in Fragment
// events that will be populated in this row_x000D_
mEventsList = (ArrayList<Event>)getArguments().getSerializable("eventsList");_x000D_
_x000D_
// description of events to be populated in this row_x000D_
mCategoryRow = (CategoryRow)getArguments().getSerializable("categoryRow");
_x000D_
To get elements of a list you have to use list[i]
instead of list(i)
.
Using bootstrap, if you need to also add some values to the option to use for filters or other stuff you can simply add the class "bs-title-option" to the option that you want as a placeholder:
<select class="form-group">
<option class="bs-title-option" value="myVal">My PlaceHolder</option>
<option>A</option>
<option>B</option>
<option>c</option>
</select>
Bootstrap adds this class to the title
attribute.
More fast way using directly a no-string array but a string:
string[] StringSplit(string StringToSplit, string Delimitator)
{
return StringToSplit.Split(new[] { Delimitator }, StringSplitOptions.None);
}
StringSplit("E' una bella giornata oggi", "giornata");
/* Output
[0] "E' una bella giornata"
[1] " oggi"
*/
I want to add something on @Michael Laffargue's post:
jqXHR.done()
is faster!
jqXHR.success()
have some load time in callback and sometimes can overkill script. I find that on hard way before.
UPDATE:
Using jqXHR.done()
, jqXHR.fail()
and jqXHR.always()
you can better manipulate with ajax request. Generaly you can define ajax in some variable or object and use that variable or object in any part of your code and get data faster. Good example:
/* Initialize some your AJAX function */
function call_ajax(attr){
var settings=$.extend({
call : 'users',
option : 'list'
}, attr );
return $.ajax({
type: "POST",
url: "//exapmple.com//ajax.php",
data: settings,
cache : false
});
}
/* .... Somewhere in your code ..... */
call_ajax({
/* ... */
id : 10,
option : 'edit_user'
change : {
name : 'John Doe'
}
/* ... */
}).done(function(data){
/* DO SOMETHING AWESOME */
});
You can use code as below when
using Image as Loading
<asp:UpdateProgress id="updateProgress" runat="server">
<ProgressTemplate>
<div style="position: fixed; text-align: center; height: 100%; width: 100%; top: 0; right: 0; left: 0; z-index: 9999999; background-color: #000000; opacity: 0.7;">
<asp:Image ID="imgUpdateProgress" runat="server" ImageUrl="~/images/ajax-loader.gif" AlternateText="Loading ..." ToolTip="Loading ..." style="padding: 10px;position:fixed;top:45%;left:50%;" />
</div>
</ProgressTemplate>
</asp:UpdateProgress>
using Text as Loading
<asp:UpdateProgress id="updateProgress" runat="server">
<ProgressTemplate>
<div style="position: fixed; text-align: center; height: 100%; width: 100%; top: 0; right: 0; left: 0; z-index: 9999999; background-color: #000000; opacity: 0.7;">
<span style="border-width: 0px; position: fixed; padding: 50px; background-color: #FFFFFF; font-size: 36px; left: 40%; top: 40%;">Loading ...</span>
</div>
</ProgressTemplate>
</asp:UpdateProgress>
<form id="upload_form" enctype="multipart/form-data">
jQuery with CodeIgniter file upload:
var formData = new FormData($('#upload_form')[0]);
formData.append('tax_file', $('input[type=file]')[0].files[0]);
$.ajax({
type: "POST",
url: base_url + "member/upload/",
data: formData,
//use contentType, processData for sure.
contentType: false,
processData: false,
beforeSend: function() {
$('.modal .ajax_data').prepend('<img src="' +
base_url +
'"asset/images/ajax-loader.gif" />');
//$(".modal .ajax_data").html("<pre>Hold on...</pre>");
$(".modal").modal("show");
},
success: function(msg) {
$(".modal .ajax_data").html("<pre>" + msg +
"</pre>");
$('#close').hide();
},
error: function() {
$(".modal .ajax_data").html(
"<pre>Sorry! Couldn't process your request.</pre>"
); //
$('#done').hide();
}
});
you can use.
var form = $('form')[0];
var formData = new FormData(form);
formData.append('tax_file', $('input[type=file]')[0].files[0]);
or
var formData = new FormData($('#upload_form')[0]);
formData.append('tax_file', $('input[type=file]')[0].files[0]);
Both will work.
I'm using Nexus 7 (4.2) on Windows 7 x64. None of the other methods described here worked for me. The tab was already in PTP mode. Finally, I could get it working when I added the below line to 'android_winusb.inf' under <android-sdk>\extras\google\usb_driver and did an 'update driver':
%CompositeAdbInterface% = USB_Install, USB\VID_18D1&PID_4E44&REV_9999&MI_01
To get the exact hardware ID (USB\VID_18D1&PID_4E44&REV_9999&MI_01 in my case), you can go to Computer Management -> Device Manager -> Details tab -> select Hardware Id from the drop-down.
No, but that is a good thing since you should always handle your errors.
There are techniques that you can employ to defer error handling, see Errors are values by Rob Pike.
ew := &errWriter{w: fd} ew.write(p0[a:b]) ew.write(p1[c:d]) ew.write(p2[e:f]) // and so on if ew.err != nil { return ew.err }
In this example from the blog post he illustrates how you could create an errWriter
type that defers error handling till you are done calling write
.
I would recommend creating a HashMap
from set A, and then iterating through set B and checking if any element of B is in A. This would run in O(|A|+|B|)
time (as there would be no collisions), whereas retainAll(Collection<?> c)
must run in O(|A|*|B|)
time.
You can use the unicode of a non breaking space :
p:before { content: "\00a0 "; }
See JSfiddle demo
[style improved by @Jason Sperske]
there are some special quotes characters which are not removed by HtmlEncode and will not be displayed in Edge or IE correctly like ” and “ . you can extent replacing these characters with something like below function.
private string RemoveJunkChars(string input)
{
return HttpUtility.HtmlEncode(input.Replace("”", "\"").Replace("“", "\""));
}
Have you tried with the custom format "#,##0.##"
?
I prefix this reply with "you shouldn't use a regular expression to parse XML -- it's only going to result in edge cases that don't work right, and a forever-increasing-in-complexity regex while you try to fix it."
That being said, you need to proceed by matching the string and grabbing the group you want:
if (m.matches())
{
String result = m.group(1);
// do something with result
}