if you are using react with hooks:
import React, { useState, useEffect } from 'react'
const AdblockDetect = () => {
const [usingAdblock, setUsingAdblock] = useState(false)
let fakeAdBanner
useEffect(() => {
if (fakeAdBanner) {
setUsingAdblock(fakeAdBanner.offsetHeight === 0)
}
})
if (usingAdblock === true) {
return null
}
return (
<div>
<div
ref={r => (fakeAdBanner = r)}
style={{ height: '1px', width: '1px', visibility: 'hidden', pointerEvents: 'none' }}
className="adBanner"
/>
Adblock!
</div>
)
}
export default AdblockDetect
Perhaps you're asking about the DOM methods appendChild
and insertBefore
.
parentNode.insertBefore(newChild, refChild)
Inserts the node
newChild
as a child ofparentNode
before the existing child noderefChild
. (ReturnsnewChild
.)If
refChild
is null,newChild
is added at the end of the list of children. Equivalently, and more readably, useparentNode.appendChild(newChild)
.
Simple and easy to understand example by using ternary operators to set selected value in php
<?php $plan = array('1' => 'Green','2'=>'Red' ); ?>
<select class="form-control" title="Choose Plan">
<?php foreach ($plan as $id=> $value) { ?>
<option value="<?php echo $id;?>" <?php echo ($id== '2') ? ' selected="selected"' : '';?>><?php echo $value;?></option>
<?php } ?>
</select>
I guess I am coming late, but this info might be useful to anyone I found out something, which might be simple but important. if you use export on a function directly i.e
export const addPost = (id) =>{
...
}
Note while importing you need to wrap it in curly braces
i.e. import {addPost} from '../URL';
But when using export default i.e
const addPost = (id) =>{
...
}
export default addPost
,
Then you can import without curly braces i.e.
import addPost from '../url';
export default addPost
I hope this helps anyone who got confused as me.
The following can generate a color from name, hex, or known name.
Color beige = StringToColor("Beige");
Color purple = StringToColor("#800080");
Color window = StringToColor("Window");
public static Color StringToColor(string colorStr)
{
TypeConverter cc = TypeDescriptor.GetConverter(typeof(Color));
var result = (Color)cc.ConvertFromString(colorStr);
return result;
}
The snippet was taken from Jo Albahari's C# in a Nutshell.
While most people have answered the question directly, I wanted to elaborate more on the concept behind it. First, I was drawn to the attention of IME when I created a default Login Activity. It generated some code for me which included the following:
<EditText
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/prompt_password"
android:imeActionId="@+id/login"
android:imeActionLabel="@string/action_sign_in_short"
android:imeOptions="actionUnspecified"
android:inputType="textPassword"
android:maxLines="1"
android:singleLine="true"/>
You should already be familiar with the inputType attribute. This just informs Android the type of text expected such as an email address, password or phone number. The full list of possible values can be found here.
It was, however, the attribute imeOptions="actionUnspecified"
that I didn't understand its purpose. Android allows you to interact with the keyboard that pops up from bottom of screen when text is selected using the InputMethodManager
. On the bottom corner of the keyboard, there is a button, typically it says "Next" or "Done", depending on the current text field. Android allows you to customize this using android:imeOptions
. You can specify a "Send" button or "Next" button. The full list can be found here.
With that, you can then listen for presses on the action button by defining a TextView.OnEditorActionListener
for the EditText
element. As in your example:
editText.setOnEditorActionListener(new EditText.OnEditorActionListener() {
@Override
public boolean onEditorAction(EditText v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
//do here your stuff f
return true;
}
return false;
}
});
Now in my example I had android:imeOptions="actionUnspecified"
attribute. This is useful when you want to try to login a user when they press the enter key. In your Activity, you can detect this tag and then attempt the login:
mPasswordView = (EditText) findViewById(R.id.password);
mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
if (id == R.id.login || id == EditorInfo.IME_NULL) {
attemptLogin();
return true;
}
return false;
}
});
Static methods in Python?
Is it possible to have static methods in Python so I can call them without initializing a class, like:
ClassName.StaticMethod()
Yes, static methods can be created like this (although it's a bit more Pythonic to use underscores instead of CamelCase for methods):
class ClassName(object):
@staticmethod
def static_method(kwarg1=None):
'''return a value that is a function of kwarg1'''
The above uses the decorator syntax. This syntax is equivalent to
class ClassName(object):
def static_method(kwarg1=None):
'''return a value that is a function of kwarg1'''
static_method = staticmethod(static_method)
This can be used just as you described:
ClassName.static_method()
A builtin example of a static method is str.maketrans()
in Python 3, which was a function in the string
module in Python 2.
Another option that can be used as you describe is the classmethod
, the difference is that the classmethod gets the class as an implicit first argument, and if subclassed, then it gets the subclass as the implicit first argument.
class ClassName(object):
@classmethod
def class_method(cls, kwarg1=None):
'''return a value that is a function of the class and kwarg1'''
Note that cls
is not a required name for the first argument, but most experienced Python coders will consider it badly done if you use anything else.
These are typically used as alternative constructors.
new_instance = ClassName.class_method()
A builtin example is dict.fromkeys()
:
new_dict = dict.fromkeys(['key1', 'key2'])
If you would like to add vector to itself both popular solutions will fail:
std::vector<std::string> v, orig;
orig.push_back("first");
orig.push_back("second");
// BAD:
v = orig;
v.insert(v.end(), v.begin(), v.end());
// Now v contains: { "first", "second", "", "" }
// BAD:
v = orig;
std::copy(v.begin(), v.end(), std::back_inserter(v));
// std::bad_alloc exception is generated
// GOOD, but I can't guarantee it will work with any STL:
v = orig;
v.reserve(v.size()*2);
v.insert(v.end(), v.begin(), v.end());
// Now v contains: { "first", "second", "first", "second" }
// GOOD, but I can't guarantee it will work with any STL:
v = orig;
v.reserve(v.size()*2);
std::copy(v.begin(), v.end(), std::back_inserter(v));
// Now v contains: { "first", "second", "first", "second" }
// GOOD (best):
v = orig;
v.insert(v.end(), orig.begin(), orig.end()); // note: we use different vectors here
// Now v contains: { "first", "second", "first", "second" }
To suppress output, use redirection to NUL
.
There are two kinds of output that console commands use:
standard output, or stdout
,
standard error, or stderr
.
Of the two, stdout
is used more often, both by internal commands, like copy
, and by console utilities, or external commands, like find
and others, as well as by third-party console programs.
>NUL
suppresses the standard output and works fine e.g. for suppressing the 1 file(s) copied.
message of the copy
command. An alternative syntax is 1>NUL
. So,
COPY file1 file2 >NUL
or
COPY file1 file2 1>NUL
or
>NUL COPY file1 file2
or
1>NUL COPY file1 file2
suppresses all of COPY
's standard output.
To suppress error messages, which are typically printed to stderr
, use 2>NUL
instead. So, to suppress a File Not Found
message that DEL
prints when, well, the specified file is not found, just add 2>NUL
either at the beginning or at the end of the command line:
DEL file 2>NUL
or
2>NUL DEL file
Although sometimes it may be a better idea to actually verify whether the file exists before trying to delete it, like you are doing in your own solution. Note, however, that you don't need to delete the files one by one, using a loop. You can use a single command to delete the lot:
IF EXIST "%scriptDirectory%*.noext" DEL "%scriptDirectory%*.noext"
In a nutshell it means.. You are trying to access an object without instantiating it.. You might need to use the "new" keyword to instantiate it first i.e create an instance of it.
For eg:
public class MyClass
{
public int Id {get; set;}
}
MyClass myClass;
myClass.Id = 0; <----------- An error will be thrown here.. because myClass is null here...
You will have to use:
myClass = new MyClass();
myClass.Id = 0;
Hope I made it clear..
Try something like this:
SET MY_PATH=C:\Folder with a space
"%MY_PATH%\MyProgram.exe" /switch1 /switch2
I used the http://www.javadecompilers.com but in some classes it gives you the message "could not load this classes..."
INSTEAD download Android Studio, navigate to the folder containing the java class file and double click it. The code will show in the right pane and I guess you can copy it an save it as a java file from there
I assume by "didn't work" you mean that it's giving you a timestamp instead of the formatted date, because you were doing it correctly:
$effectiveDate = strtotime("+3 months", strtotime($effectiveDate)); // returns timestamp
echo date('Y-m-d',$effectiveDate); // formatted version
Why for
? What do you want to iterate? Try this.
call :cpy pc-name-1
call :cpy pc-name-2
...
:cpy
net use \\%1\{destfolder} {password} /user:{username}
copy {file} \\%1\{destfolder}
goto :EOF
One possible solution that I use is to use python3. It seems to solve many utf issues.
Sorry for the late answer, but it may help people in the future.
For example,
#!/usr/bin/env python3
import json
# your code follows
If you need to debug an application working on Tomcat, make sure that your Tomcat-folder/bin/startup.bat (if using windows) contains the following lines:
set JPDA_TRANSPORT="dt_socket"
set JPDA_ADDRESS=8000
call "%EXECUTABLE%" jpda start %CMD_LINE_ARGS%
For straight HTML, with no JavaScript required:
<a href="#something">Add '#something' to URL</a>
Or, to take your question more literally, to just add '#' to the URL:
<a href="#">Add '#' to URL</a>
Bootstrap is an HTML, CSS, JS framework with many components that let you create beautiful and modern web sites or web applications very fast.
The following websites contain examples, elements and reusable components that you can integrate into your project using bootstrap framework
I believe you are executing all these statements differently
executing together will result => 38 ,29
int a=5,i;
i=++a + ++a + a++;
//this means i= 6+7+7=20 and when this result is stored in i,
//then last *a* will be incremented <br>
i=a++ + ++a + ++a;
//this means i= 5+7+8=20 (this could be complicated,
//but its working like this),<br>
a=++a + ++a + a++;
//as a is 6+7+7=20 (this is incremented like this)
DECLARE @JCnt int=null
SEt @JCnt=(SELECT COUNT( ISNUll(EmpCode,0)) FROM tbl_Employees WHERE EmpCode=1 )
UPDATE #TempCode
SET janCA= CASE WHEN @JCnt>0 THEN (SELECT SUM (ISNUll(Amount,0)) FROM tbl_Salary WHERE Code=1 )ELSE 0 END
WHERE code=1
This will search text in all the td's inside each tr and show/hide tr's based on search text
$.each($(".table tbody").find("tr"), function () {
if ($(this).text().toLowerCase().replace(/\s+/g, '').indexOf(searchText.replace(/\s+/g, '').toLowerCase()) == -1)
$(this).hide();
else
$(this).show();
});
The shebang is a directive to the loader to use the program which is specified after the #!
as the interpreter for the file in question when you try to execute it. So, if you try to run a file called foo.sh
which has #!/bin/bash
at the top, the actual command that runs is /bin/bash foo.sh
. This is a flexible way of using different interpreters for different programs. This is something implemented at the system level and the user level API is the shebang convention.
It's also worth knowing that the shebang is a magic number - a human readable one that identifies the file as a script for the given interpreter.
Your point about it "working" even without the shebang is only because the program in question is a shell script written for the same shell as the one you are using. For example, you could very well write a javascript file and then put a #! /usr/bin/js
(or something similar) to have a javascript "Shell script".
Assuming you're the administrator of the machine, Ubuntu has granted you the right to sudo to run any command as any user.
Also assuming you did not restrict the rights in the pg_hba.conf
file (in the /etc/postgresql/9.1/main
directory), it should contain this line as the first rule:
# Database administrative login by Unix domain socket
local all postgres peer
(About the file location: 9.1
is the major postgres version and main
the name of your "cluster". It will differ if using a newer version of postgres or non-default names. Use the pg_lsclusters
command to obtain this information for your version/system).
Anyway, if the pg_hba.conf
file does not have that line, edit the file, add it, and reload the service with sudo service postgresql reload
.
Then you should be able to log in with psql
as the postgres superuser with this shell command:
sudo -u postgres psql
Once inside psql, issue the SQL command:
ALTER USER postgres PASSWORD 'newpassword';
In this command, postgres
is the name of a superuser. If the user whose password is forgotten was ritesh
, the command would be:
ALTER USER ritesh PASSWORD 'newpassword';
References: PostgreSQL 9.1.13 Documentation, Chapter 19. Client Authentication
Keep in mind that you need to type postgres with a single S at the end
If leaving the password in clear text in the history of commands or the server log is a problem, psql provides an interactive meta-command to avoid that, as an alternative to ALTER USER ... PASSWORD
:
\password username
It asks for the password with a double blind input, then hashes it according to the password_encryption
setting and issue the ALTER USER
command to the server with the hashed version of the password, instead of the clear text version.
Only For API level >= 24
Copy any text from your local machine and then simply run this command
adb shell input keyevent 279
Make sure In Android Emulator Settings the Enable Clipboard Sharing
options is enabled
as the exception says there is already another server running on the same port. you can either kill that service or change glassfish to run on another poet
This sounds more like you want a tooltip for the link selected. There are many jQuery tooltips, try out jQuery qTip. It has a lot of options and is easy to change the styles.
Otherwise if you want to do this yourself you can use the jQuery .position()
. More info about .position()
is on http://api.jquery.com/position/
$("#element").position();
will return the current position of an element relative to the offset parent.
There is also the jQuery .offset(); which will return the position relative to the document.
I very often use regex to extract data from files I just used that to replace the literal quote \"
with //
nothing :-)
cat file.csv | egrep '^\"([0-9]{1,3}\.[0-9]{1,3}\.)' | sed s/\"//g | cut -d, -f1 > list.txt
Using Pygrok, you can define abstracted extensions to the Regular Expression syntax.
The custom patterns can be included in your regex in the format %{PATTERN_NAME}
.
You can also create a label for that pattern, by separating with a colon: %s{PATTERN_NAME:matched_string}
. If the pattern matches, the value will be returned as part of the resulting dictionary (e.g. result.get('matched_string')
)
For example:
from pygrok import Grok
input_string = 'monkey 2010-07-10 love banana'
date_pattern = '%{YEAR:year}-%{MONTHNUM:month}-%{MONTHDAY:day}'
grok = Grok(date_pattern)
print(grok.match(input_string))
The resulting value will be a dictionary:
{'month': '07', 'day': '10', 'year': '2010'}
If the date_pattern does not exist in the input_string, the return value will be None
. By contrast, if your pattern does not have any labels, it will return an empty dictionary {}
References:
Also you can use this code: moment("yourDateHere", "YYYY-MM-DD").fromNow(). This will calculate the difference between today and your provided date.
you can use any of the following five ways to hide element, depends upon your requirements.
.hide {
opacity: 0;
}
.hide {
visibility: hidden;
}
.hide {
display: none;
}
.hide {
position: absolute;
top: -9999px;
left: -9999px;
}
.hide {
clip-path: polygon(0px 0px,0px 0px,0px 0px,0px 0px);
}
To show use any of the following: opacity: 1; visibility: visible; display: block;
Source : https://www.sitepoint.com/five-ways-to-hide-elements-in-css/
On a Windows machine, the .m2 folder is expected to be located under ${user.home}
. On Windows 7 and Vista this resolves to <root>\Users\<username>
and on XP it is <root>\Documents and Settings\<username>\.m2
. So you'd normally see it under c:\Users\Jonathan\.m2
.
If you want to create a folder with a .
prefix on Windows, you can simply do this on the command line.
Note that you don't actually need the .m2 location unless you want to create a distinct user settings file, which is optional (see the Settings reference for more details).
If you don't need a separate user settings file and don't really want the local repository under your user home you can simply set the location of your repository to a different folder by modifying the global settings file (located in \conf\settings.xml).
The following snippet would set the local repository to c:\Maven\repository
for example:
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
http://maven.apache.org/xsd/settings-1.0.0.xsd">
<localRepository>c:\Maven\repository</localRepository>
...
In Scripting languages like (JavaScript and old PHP versions) we use existing fundamental functions and method for performing our job.
Lets take an example in JavaScript
we can use ajax
or web-sockets
only if they are supported by browser or methods exist or them in browser. But in languages like C or C++ , Java we can write that feature from scratch even if any library for that feature is not available but we can't do so in JavaScript.
can you support web-sockets in Internet Explorer 8 or prior with the help of JavaScript But you can write a plugin in C or C++ or Java which may add a feature of web-socket to Internet Explorer 8.
Basically in Scripting languages we write a code in a sequence which execute existing methods in a sequence to complete our job. Entering numbers and formula in a digital calculator to do a operation is also a very example of scripting language.We should note that the compiler/run-time-environment of every scripting language is always written in programming language in which we can add more features and methods and can write new libraries.
PHP This is language which is somewhat b/w programming and scripting. We can add new methods by adding compiled extensions written in another High Level Language. We can't add high level features of networking or creating image processing libraries directly in PHP.
P.S. I am really sorry for revolving my answer around PHP JavaScript only but I use these two because I have a considerable experience in these two.
fyi <form>
supports :before
/ :after
as well, might be of help if you wrap your <input>
element with it... (got myself a design issue with that too)
Register the EventEmitter
in your child component as the @Output
:
@Output() onDatePicked = new EventEmitter<any>();
Emit value on click:
public pickDate(date: any): void {
this.onDatePicked.emit(date);
}
Listen for the events in your parent component's template:
<div>
<calendar (onDatePicked)="doSomething($event)"></calendar>
</div>
and in the parent component:
public doSomething(date: any):void {
console.log('Picked date: ', date);
}
It's also well explained in the official docs: Component interaction.
Thread.sleep can throw an InterruptedException which is a checked exception. All checked exceptions must either be caught and handled or else you must declare that your method can throw it. You need to do this whether or not the exception actually will be thrown. Not declaring a checked exception that your method can throw is a compile error.
You either need to catch it:
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
// handle the exception...
// For example consider calling Thread.currentThread().interrupt(); here.
}
Or declare that your method can throw an InterruptedException
:
public static void main(String[]args) throws InterruptedException
Related
One way is to use the jQuery offset
method to translate the event.pageX
and event.pageY
coordinates from the event into a mouse position relative to the parent. Here's an example for future reference:
$("#something").click(function(e){
var parentOffset = $(this).parent().offset();
//or $(this).offset(); if you really just want the current element's offset
var relX = e.pageX - parentOffset.left;
var relY = e.pageY - parentOffset.top;
});
You didn't create your project as "Dynamic Web Project", so Eclipse doesn't recognize it like a web project. Create a new "Dynamic Web Project" or go to Properties ? Projects Facets and check Dynamic Web Module.
You can also use any()
, map()
like so:
if any(map(l.startswith, x)):
pass # Do something
Or alternatively, using a generator expression:
if any(l.startswith(s) for s in x)
pass # Do something
You can try like below
DECLARE @sqlCommand NVARCHAR(4000)
DECLARE @ID INT
DECLARE @Name NVARCHAR(100)
SET @ID = 4
SET @sqlCommand = 'SELECT @Name = [Name]
FROM [AdventureWorks2014].[HumanResources].[Department]
WHERE DepartmentID = @ID'
EXEC sp_executesql @sqlCommand, N'@ID INT, @Name NVARCHAR(100) OUTPUT',
@ID = @ID, @Name = @Name OUTPUT
SELECT @Name ReturnedName
Source : blog.sqlauthority.com
<html>
<body>
<p>Enter some text in the fields below, and then press the "Submit form" button to submit the form.</p>
<form id="myForm" action="/action_page.php">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br><br>
<input type="button" onclick="myFunction()" value="Submit form">
</form>
<script>
function myFunction() {
document.getElementById("myForm").submit();
}
</script>
</body>
</html>
__del__
is a finalizer. It is called when an object is garbage collected which happens at some point after all references to the object have been deleted.
In a simple case this could be right after you say del x
or, if x
is a local variable, after the function ends. In particular, unless there are circular references, CPython (the standard Python implementation) will garbage collect immediately.
However, this is an implementation detail of CPython. The only required property of Python garbage collection is that it happens after all references have been deleted, so this might not necessary happen right after and might not happen at all.
Even more, variables can live for a long time for many reasons, e.g. a propagating exception or module introspection can keep variable reference count greater than 0. Also, variable can be a part of cycle of references β CPython with garbage collection turned on breaks most, but not all, such cycles, and even then only periodically.
Since you have no guarantee it's executed, one should never put the code that you need to be run into __del__()
β instead, this code belongs to finally
clause of the try
block or to a context manager in a with
statement. However, there are valid use cases for __del__
: e.g. if an object X
references Y
and also keeps a copy of Y
reference in a global cache
(cache['X -> Y'] = Y
) then it would be polite for X.__del__
to also delete the cache entry.
If you know that the destructor provides (in violation of the above guideline) a required cleanup, you might want to call it directly, since there is nothing special about it as a method: x.__del__()
. Obviously, you should you do so only if you know that it doesn't mind to be called twice. Or, as a last resort, you can redefine this method using
type(x).__del__ = my_safe_cleanup_method
$this->db->insert_id();
Returns the insert ID number when performing database inserts
Query Helper Methods for codeigniter-3
dynDiv.Attributes["class"] = "myCssClass";
$ends_with = strrchr($text, '.'); // Ends with dot
$start_with = (0 === strpos($text, '.')); // Starts with dot
Yes, this is confusing...
According to this blog post, it looks like this is an omission from WPF.
To make it work you need to use a style:
<Border Name="ClearButtonBorder" Grid.Column="1" CornerRadius="0,3,3,0">
<Border.Style>
<Style>
<Setter Property="Border.Background" Value="Blue"/>
<Style.Triggers>
<Trigger Property="Border.IsMouseOver" Value="True">
<Setter Property="Border.Background" Value="Green" />
</Trigger>
</Style.Triggers>
</Style>
</Border.Style>
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="X" />
</Border>
I guess this problem isn't that common as most people tend to factor out this sort of thing into a style, so it can be used on multiple controls.
Math.Round(inputValue, 2, MidpointRounding.AwayFromZero)
I had similar issue running emulator from android studio everytime, or on a physical device. Instead, you can quickly run android emulator from command line,
android avd
Once the emulator is running, you can check with adb devices
if the emulator shows up.
Then you can simply use
react-native run-android
to run the app on the emulator.
Make sure you've platform tools installed to be able to use adb
. Or you can use
brew install android-platform-tools
A thread is something like some branch. Multi-branched means when there are at least two branches. If the branches are reduced, then the minimum remains one. This one is although like the branches removed, but in general we do not consider it branch.
Similarly when there are at least two threads we call it multi-threaded program. If the threads are reduced, the minimum remains one. Hello program is a single threaded program, but no one needs to know multi-threading to write or run it.
In simple words when a program is not said to be having threads, it means that the program is not a multi-threaded program, more over in true sense it is a single threaded program, in which YOU CAN put your code as if it is multi-threaded.
Below a useless code is given, but it will suffice to do away with your some confusions about Runnable
. It will print "Hello World".
class NamedRunnable implements Runnable {
public void run() { // The run method prints a message to standard output.
System.out.println("Hello World");
}
public static void main(String[]arg){
NamedRunnable namedRunnable = new NamedRunnable( );
namedRunnable.run();
}
}
Instead, try:
var now = new Date();
current = new Date(now.getFullYear(), now.getMonth()+1, 1);
In my case opening 'Help' >> "Install New Software" had no entries for any URLs (previous url's were not there) - so I Manually added 'em. And updated ... and Voilaaaa !! Above posts have been very helpful in resolving this issue for me.
try this.
table
{
background-color: #aaa;
}
tbody
{
background-color: #ddd;
height: 100px;
overflow-y: scroll;
position: absolute;
}
td
{
padding: 3px 10px;
color: green;
width: 100px;
}
Add two bindings to your website, one for local access and another for LAN access like so:
Open IIS and select your local website (that you want to access from your local network) from the left panel:
Connections > server (user-pc) > sites > local site
Open Bindings on the right panel under Actions tab add these bindings:
Local:
Type: http Ip Address: All Unassigned Port: 80 Host name: samplesite.local
LAN:
Type: http Ip Address: <Network address of the hosting machine ex. 192.168.0.10> Port: 80 Host name: <Leave it blank>
Voila, you should be able to access the website from any machine on your local network by using the host's LAN IP address (192.168.0.10 in the above example) as the site url.
NOTE:
if you want to access the website from LAN using a host name (like samplesite.local) instead of an ip address, add the host name to the hosts file on the local network machine (The hosts file can be found in "C:\Windows\System32\drivers\etc\hosts" in windows, or "/etc/hosts" in ubuntu):
192.168.0.10 samplesite.local
Removing the name from your binding will make it apply to all endpoints, and should produce the desired results. As so:
<services>
<service name="Service.IService">
<clear />
<endpoint binding="basicHttpBinding" contract="Service.IService" />
</service>
</services>
<bindings>
<basicHttpBinding>
<binding maxBufferSize="2147483647" maxReceivedMessageSize="2147483647">
<readerQuotas maxDepth="32" maxStringContentLength="2147483647"
maxArrayLength="16348" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
</binding>
</basicHttpBinding>
<webHttpBinding>
<binding maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" />
</webHttpBinding>
</bindings>
Also note that I removed the bindingConfiguration
attribute from the endpoint node. Otherwise you would get an exception.
This same solution was found here : Problem with large requests in WCF
ListaServizi.Sort();
Will do that for you. It's straightforward enough with a list of strings. You need to be a little cleverer if sorting objects.
var input= $(this);
input.innerHTML = '';
as Jon B said, but you'll also want to check for the ApplicationExitCall
and TaskManagerClosing
CloseReason:
protected override void OnFormClosing(FormClosingEventArgs e)
{
if ( e.CloseReason == CloseReason.WindowsShutDown
||e.CloseReason == CloseReason.ApplicationExitCall
||e.CloseReason == CloseReason.TaskManagerClosing) {
return;
}
e.Cancel = true;
//assuming you want the close-button to only hide the form,
//and are overriding the form's OnFormClosing method:
this.Hide();
}
To link to a form you need:
Form2 form2 = new Form2();
form2.show();
this.hide();
then hide the previous form
In my case the class was registered properly and built in ANY CPU / 64 bit mode.
But the Enable 32-bit Applications property of the IIS Application pool of the application which uses the class was set to True.
Class was not found because of the architecture mismatch between the application pool configuration and the actual registered class.
Setting Enable 32-bit Applications to False fixed the issue.
Something like that should be what you need
private void button1_Click(object sender, RoutedEventArgs e)
{
// Create OpenFileDialog
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
// Set filter for file extension and default file extension
dlg.DefaultExt = ".png";
dlg.Filter = "JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif";
// Display OpenFileDialog by calling ShowDialog method
Nullable<bool> result = dlg.ShowDialog();
// Get the selected file name and display in a TextBox
if (result == true)
{
// Open document
string filename = dlg.FileName;
textBox1.Text = filename;
}
}
As I said in a comment to aqingsao's answer, it doesn't quite work when the textarea
has newline characters, at least on Windows.
I've change his answer slightly thus:
$(function() {
$("textarea[maxlength]").bind('input propertychange', function() {
var maxLength = $(this).attr('maxlength');
//I'm guessing JavaScript is treating a newline as one character rather than two so when I try to insert a "max length" string into the database I get an error.
//Detect how many newlines are in the textarea, then be sure to count them twice as part of the length of the input.
var newlines = ($(this).val().match(/\n/g) || []).length
if ($(this).val().length + newlines > maxLength) {
$(this).val($(this).val().substring(0, maxLength - newlines));
}
})
});
Now when I try to paste a lot of data in with newlines, I get exactly the right number of characters.
Now we need to create a drawable resource file and name it ripple_effect as shown below
ripple_effect.xml
<?xml version="1.0" encoding="utf-8"?>
<ripple
xmlns:android="http://schemas.android.com/apk/res/android"
android:color="@color/colorRipple"> <!-- ripple color -->
<!-- for Button -->
<item>
<shape android:shape="rectangle">
<corners android:radius="3dp" />
<solid android:color="@color/colorPrimary"/>
</shape>
</item>
</ripple>
Source Full: https://code-android-example.blogspot.com/2020/11/ripple-effect-in-android-for-button.html
The inner exception of bug says Could not load file or assembly 'log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=692fbea5521e1304'
Changing the AppPool setting False for Enable 32-bit Application solved the issue
The semicolon character is used to terminate the SQL statement.
You can either use #
signs around a date value or use Access's (ACE, Jet, whatever) cast to DATETIME
function CDATE()
. As its name suggests, DATETIME
always includes a time element so your literal values should reflect this fact. The ISO date format is understood perfectly by the SQL engine.
Best not to use BETWEEN
for DATETIME
in Access: it's modelled using a floating point type and anyhow time is a continuum ;)
DATE
and TABLE
are reserved words in the SQL Standards, ODBC and Jet 4.0 (and probably beyond) so are best avoided for a data element names:
Your predicates suggest open-open representation of periods (where neither its start date or the end date is included in the period), which is arguably the least popular choice. It makes me wonder if you meant to use closed-open representation (where neither its start date is included but the period ends immediately prior to the end date):
SELECT my_date
FROM MyTable
WHERE my_date >= #2008-09-01 00:00:00#
AND my_date < #2010-09-01 00:00:00#;
Alternatively:
SELECT my_date
FROM MyTable
WHERE my_date >= CDate('2008-09-01 00:00:00')
AND my_date < CDate('2010-09-01 00:00:00');
If you use .Net 4.5 you can also use standard .Net json serializer:
using System.Runtime.Serialization.Json;
...
Stream jsonSource = ...; // serializer will read data stream
var s = new DataContractJsonSerializer(typeof(string[][]));
var j = (string[][])s.ReadObject(jsonSource);
In .Net 4.5 and older you can use JavaScriptSerializer class:
using System.Web.Script.Serialization;
...
JavaScriptSerializer serializer = new JavaScriptSerializer();
string[][] list = serializer.Deserialize<string[][]>(json);
To get lazy loading working on nullable one-to-one mappings you need to let hibernate do compile time instrumentation and add a @LazyToOne(value = LazyToOneOption.NO_PROXY)
to the one-to-one relation.
Example Mapping:
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name="other_entity_fk")
@LazyToOne(value = LazyToOneOption.NO_PROXY)
public OtherEntity getOther()
Example Ant Build file extension (for doing the Hibernate compile time instrumentation):
<property name="src" value="/your/src/directory"/><!-- path of the source files -->
<property name="libs" value="/your/libs/directory"/><!-- path of your libraries -->
<property name="destination" value="/your/build/directory"/><!-- path of your build directory -->
<fileset id="applibs" dir="${libs}">
<include name="hibernate3.jar" />
<!-- include any other libraries you'll need here -->
</fileset>
<target name="compile">
<javac srcdir="${src}" destdir="${destination}" debug="yes">
<classpath>
<fileset refid="applibs"/>
</classpath>
</javac>
</target>
<target name="instrument" depends="compile">
<taskdef name="instrument" classname="org.hibernate.tool.instrument.javassist.InstrumentTask">
<classpath>
<fileset refid="applibs"/>
</classpath>
</taskdef>
<instrument verbose="true">
<fileset dir="${destination}">
<!-- substitute the package where you keep your domain objs -->
<include name="/com/mycompany/domainobjects/*.class"/>
</fileset>
</instrument>
</target>
try this (a2 is BLOB col)
PreparedStatement ps1 = conn.prepareStatement("update t1 set a2=? where id=1");
Blob blob = conn.createBlob();
blob.setBytes(1, str.getBytes());
ps1.setBlob(1, blob);
ps1.executeUpdate();
it may work even without BLOB, driver will transform types automatically:
ps1.setBytes(1, str.getBytes);
ps1.setString(1, str);
Besides if you work with text CLOB seems to be a more natural col type
Try:
SELECT * FROM information_schema.statistics
WHERE table_schema = [DATABASE NAME]
AND table_name = [TABLE NAME] AND column_name = [COLUMN NAME]
It will tell you if there is an index of any kind on a certain column without the need to know the name given to the index. It will also work in a stored procedure (as opposed to show index)
Use FUNCTION:
CREATE OR REPLACE FUNCTION test_function
RETURN VARCHAR2 IS
BEGIN
RETURN 'This is being returned from a function';
END test_function;
For MacOS
Sometimes the ng
command does not get established as a link in /usr/local/bin
. I fixed the problem by adding it manually:
ln -s /usr/local/Cellar/node/10.10.0/lib/node_modules/angular-cli/bin/ng /usr/local/bin/ng
I won't repeat the usual stuff about Using or freeing un-managed resources, that has all been covered. But I would like to point out what seems a common misconception.
Given the following code
Public Class LargeStuff Implements IDisposable Private _Large as string() 'Some strange code that means _Large now contains several million long strings. Public Sub Dispose() Implements IDisposable.Dispose _Large=Nothing End Sub
I realise that the Disposable implementation does not follow current guidelines, but hopefully you all get the idea.
Now, when Dispose is called, how much memory gets freed?
Answer: None.
Calling Dispose can release unmanaged resources, it CANNOT reclaim managed memory, only the GC can do that. Thats not to say that the above isn't a good idea, following the above pattern is still a good idea in fact. Once Dispose has been run, there is nothing stopping the GC re-claiming the memory that was being used by _Large, even though the instance of LargeStuff may still be in scope. The strings in _Large may also be in gen 0 but the instance of LargeStuff might be gen 2, so again, memory would be re-claimed sooner.
There is no point in adding a finaliser to call the Dispose method shown above though. That will just DELAY the re-claiming of memory to allow the finaliser to run.
git config --global diff.tool vimdiff
git config --global difftool.prompt false
Typing git difftool
yields the expected behavior.
:qa
in vim cycles to the next file in the changeset without saving anything.git config --global alias.d difftool
.. will let you type git d
to invoke vimdiff.
:wq
in vim cycles to the next file in the changeset with changes saved.All the answers posted do not apply today. For example, getDrawable() is deprecated. Here is an updated answer, cheers!
ContextCompat.getDrawable(mContext, drawable)
From documented method
public static final android.graphics.drawable.Drawable getDrawable(@NotNull android.content.Context context,
@android.support.annotation.DrawableRes int id
Design patterns aren't trivially reusable solutions.
Design patterns are reusable, by definition. They're patterns you detect in other good solutions.
A pattern is not trivially reusable. You can implement your down design following the pattern however.
Relational design patters include things like:
One-to-Many relationships (master-detail, parent-child) relationships using a foreign key.
Many-to-Many relationships with a bridge table.
Optional one-to-one relationships managed with NULLs in the FK column.
Star-Schema: Dimension and Fact, OLAP design.
Fully normalized OLTP design.
Multiple indexed search columns in a dimension.
"Lookup table" that contains PK, description and code value(s) used by one or more applications. Why have code? I don't know, but when they have to be used, this is a way to manage the codes.
Uni-table. [Some call this an anti-pattern; it's a pattern, sometimes it's bad, sometimes it's good.] This is a table with lots of pre-joined stuff that violates second and third normal form.
Array table. This is a table that violates first normal form by having an array or sequence of values in the columns.
Mixed-use database. This is a database normalized for transaction processing but with lots of extra indexes for reporting and analysis. It's an anti-pattern -- don't do this. People do it anyway, so it's still a pattern.
Most folks who design databases can easily rattle off a half-dozen "It's another one of those"; these are design patterns that they use on a regular basis.
And this doesn't include administrative and operational patterns of use and management.
an algorithmic solution:
list1 = [3,2,4,1, 1]
list2 = ['three', 'two', 'four', 'one', 'one2']
lis = [(list1[i], list2[i]) for i in range(len(list1))]
list1.sort()
list2 = [x[1] for i in range(len(list1)) for x in lis if x[0] == i]
Outputs: ->
Output speed: 0.2s
>>>list1
>>>[1, 1, 2, 3, 4]
>>>list2
>>>['one', 'one2', 'two', 'three', 'four']
You probably are looking for find_in_set
function:
Where find_in_set($needle,'column') > 0
This function acts like in_array
function in PHP
If you faced this issue with your Flutter project while building in Release mode - that's what helped me:
ios
and build_ios
from your project folder.ios
module by executing flutter create .
from your project folder.open Xcode and:
execute pod install
from your project folder
flutter pub get
from your project foldernow open your Xcode and build or archive it: Product > Build (or Archive)
If your array is static or global it's initialized to zero before main() starts. That would be the most efficient option.
To sum it all up;
function toHex(i, pad) {
if (typeof(pad) === 'undefined' || pad === null) {
pad = 2;
}
var strToParse = i.toString(16);
while (strToParse.length < pad) {
strToParse = "0" + strToParse;
}
var finalVal = parseInt(strToParse, 16);
if ( finalVal < 0 ) {
finalVal = 0xFFFFFFFF + finalVal + 1;
}
return finalVal;
}
However, if you don't need to convert it back to an integer at the end (i.e. for colors), then just making sure the values aren't negative should suffice.
patrick dw's answer is right on.
For kicks and giggles I thought I would post a simple way to return an array of all the IDs.
var arrayOfIds = $.map($(".myClassName"), function(n, i){
return n.id;
});
alert(arrayOfIds);
Head stuck in jq for too long. This will work.
function addRowHandlers() {
var table = document.getElementById("tableId");
var rows = table.getElementsByTagName("tr");
for (i = 1; i < rows.length; i++) {
var row = table.rows[i];
row.onclick = function(myrow){
return function() {
var cell = myrow.getElementsByTagName("td")[0];
var id = cell.innerHTML;
alert("id:" + id);
};
}(row);
}
}
I had a similar problem and wrote a detailed article about it. If anyone has the same problem, feel free to read my article.
https://developer-blog.net/administration/ssl-zertifikat-installieren/
It is a detailed problem description in German language.
These are timeout values enforced by JVM for TCP connection establishment and waiting on reading data from socket.
If the value is set to infinity, you will not wait forever. It simply means JVM doesn't have timeout and OS will be responsible for all the timeouts. However, the timeouts on OS may be really long. On some slow network, I've seen timeouts as long as 6 minutes.
Even if you set the timeout value for socket, it may not work if the timeout happens in the native code. We can reproduce the problem on Linux by connecting to a host blocked by firewall or unplugging the cable on switch.
The only safe approach to handle TCP timeout is to run the connection code in a different thread and interrupt the thread when it takes too long.
It is possible but, before git 2.9.3 (august 2016), a git push
would print the full url used when pushing back to the cloned repo.
That would include your username and password!
But no more: See commit 68f3c07 (20 Jul 2016), and commit 882d49c (14 Jul 2016) by Jeff King (peff
).
(Merged by Junio C Hamano -- gitster
-- in commit 71076e1, 08 Aug 2016)
push
: anonymize URL in status outputCommit 47abd85 (fetch: Strip usernames from url's before storing them, 2009-04-17, Git 1.6.4) taught fetch to anonymize URLs.
The primary purpose there was to avoid sticking passwords in merge-commit messages, but as a side effect, we also avoid printing them to stderr.The push side does not have the merge-commit problem, but it probably should avoid printing them to stderr. We can reuse the same anonymizing function.
Note that for this to come up, the credentials would have to appear either on the command line or in a git config file, neither of which is particularly secure.
So people should be switching to using credential helpers instead, which makes this problem go away.But that's no excuse not to improve the situation for people who for whatever reason end up using credentials embedded in the URL.
The only subquery appears to be this - try adding a ROWNUM
limit to the where to be sure:
(SELECT C.I_WORKDATE
FROM T_COMPENSATION C
WHERE C.I_COMPENSATEDDATE = A.I_REQDATE AND ROWNUM <= 1
AND C.I_EMPID = A.I_EMPID)
You do need to investigate why this isn't unique, however - e.g. the employee might have had more than one C.I_COMPENSATEDDATE
on the matched date.
For performance reasons, you should also see if the lookup subquery can be rearranged into an inner / left join, i.e.
SELECT
...
REPLACE(TO_CHAR(C.I_WORKDATE, 'DD-Mon-YYYY'),
' ',
'') AS WORKDATE,
...
INNER JOIN T_EMPLOYEE_MS E
...
LEFT OUTER JOIN T_COMPENSATION C
ON C.I_COMPENSATEDDATE = A.I_REQDATE
AND C.I_EMPID = A.I_EMPID
...
The reason it's failing is not because it isn't signed but because the root certificate isn't trusted by your client. Rather than switch off SSL validation, an alternative approach would be to add the root CA cert to the list of CAs your app trusts.
This is the root CA cert that your app currently doesn't trust:
-----BEGIN CERTIFICATE-----
MIIFnDCCBISgAwIBAgIBZDANBgkqhkiG9w0BAQsFADBbMQswCQYDVQQGEwJDWjEs
MCoGA1UECgwjxIxlc2vDoSBwb8WhdGEsIHMucC4gW0nEjCA0NzExNDk4M10xHjAc
BgNVBAMTFVBvc3RTaWdudW0gUm9vdCBRQ0EgMjAeFw0xMDAxMTkwODA0MzFaFw0y
NTAxMTkwODA0MzFaMFsxCzAJBgNVBAYTAkNaMSwwKgYDVQQKDCPEjGVza8OhIHBv
xaF0YSwgcy5wLiBbScSMIDQ3MTE0OTgzXTEeMBwGA1UEAxMVUG9zdFNpZ251bSBS
b290IFFDQSAyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoFz8yBxf
2gf1uN0GGXknvGHwurpp4Lw3ZPWZB6nEBDGjSGIXK0Or6Xa3ZT+tVDTeUUjT133G
7Vs51D6z/ShWy+9T7a1f6XInakewyFj8PT0EdZ4tAybNYdEUO/dShg2WvUyfZfXH
0jmmZm6qUDy0VfKQfiyWchQRi/Ax6zXaU2+X3hXBfvRMr5l6zgxYVATEyxCfOLM9
a5U6lhpyCDf2Gg6dPc5Cy6QwYGGpYER1fzLGsN9stdutkwlP13DHU1Sp6W5ywtfL
owYaV1bqOOdARbAoJ7q8LO6EBjyIVr03mFusPaMCOzcEn3zL5XafknM36Vqtdmqz
iWR+3URAUgqE0wIDAQABo4ICaTCCAmUwgaUGA1UdHwSBnTCBmjAxoC+gLYYraHR0
cDovL3d3dy5wb3N0c2lnbnVtLmN6L2NybC9wc3Jvb3RxY2EyLmNybDAyoDCgLoYs
aHR0cDovL3d3dzIucG9zdHNpZ251bS5jei9jcmwvcHNyb290cWNhMi5jcmwwMaAv
oC2GK2h0dHA6Ly9wb3N0c2lnbnVtLnR0Yy5jei9jcmwvcHNyb290cWNhMi5jcmww
gfEGA1UdIASB6TCB5jCB4wYEVR0gADCB2jCB1wYIKwYBBQUHAgIwgcoagcdUZW50
byBrdmFsaWZpa292YW55IHN5c3RlbW92eSBjZXJ0aWZpa2F0IGJ5bCB2eWRhbiBw
b2RsZSB6YWtvbmEgMjI3LzIwMDBTYi4gYSBuYXZhem55Y2ggcHJlZHBpc3UvVGhp
cyBxdWFsaWZpZWQgc3lzdGVtIGNlcnRpZmljYXRlIHdhcyBpc3N1ZWQgYWNjb3Jk
aW5nIHRvIExhdyBObyAyMjcvMjAwMENvbGwuIGFuZCByZWxhdGVkIHJlZ3VsYXRp
b25zMBIGA1UdEwEB/wQIMAYBAf8CAQEwDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQW
BBQVKYzFRWmruLPD6v5LuDHY3PDndjCBgwYDVR0jBHwweoAUFSmMxUVpq7izw+r+
S7gx2Nzw53ahX6RdMFsxCzAJBgNVBAYTAkNaMSwwKgYDVQQKDCPEjGVza8OhIHBv
xaF0YSwgcy5wLiBbScSMIDQ3MTE0OTgzXTEeMBwGA1UEAxMVUG9zdFNpZ251bSBS
b290IFFDQSAyggFkMA0GCSqGSIb3DQEBCwUAA4IBAQBeKtoLQKFqWJEgLNxPbQNN
5OTjbpOTEEkq2jFI0tUhtRx//6zwuqJCzfO/KqggUrHBca+GV/qXcNzNAlytyM71
fMv/VwgL9gBHTN/IFIw100JbciI23yFQTdF/UoEfK/m+IFfirxSRi8LRERdXHTEb
vwxMXIzZVXloWvX64UwWtf4Tvw5bAoPj0O1Z2ly4aMTAT2a+y+z184UhuZ/oGyMw
eIakmFM7M7RrNki507jiSLTzuaFMCpyWOX7ULIhzY6xKdm5iQLjTvExn2JTvVChF
Y+jUu/G0zAdLyeU4vaXdQm1A8AEiJPTd0Z9LAxL6Sq2iraLNN36+NyEK/ts3mPLL
-----END CERTIFICATE-----
You can decode and view this certificate using
I was facing same issue. I did not put @ResponseBody
since I was using @RestController
. But still I was getting error because I did not put the getter/setter
method for the Company class. So after putting the getter/setter
my problem was resolved.
If I understand the situation correctly, you are just passing json data through the http body, instead of application/x-www-form-urlencoded
data.
You can fetch this data with this snippet:
$request_body = file_get_contents('php://input');
If you are passing json, then you can do:
$data = json_decode($request_body);
$data
then contains the json data is php array.
php://input
is a so called wrapper.
php://input is a read-only stream that allows you to read raw data from the request body. In the case of POST requests, it is preferable to use php://input instead of $HTTP_RAW_POST_DATA as it does not depend on special php.ini directives. Moreover, for those cases where $HTTP_RAW_POST_DATA is not populated by default, it is a potentially less memory intensive alternative to activating always_populate_raw_post_data. php://input is not available with enctype="multipart/form-data".
You cannot break a forEach
in underscore, as it emulates EcmaScript 5 native behaviour.
Your second way is correct.
def foo(opts: dict = {}):
pass
print(foo.__annotations__)
this outputs
{'opts': <class 'dict'>}
It's true that's it's not listed in PEP 484, but type hints are an application of function annotations, which are documented in PEP 3107. The syntax section makes it clear that keyword arguments works with function annotations in this way.
I strongly advise against using mutable keyword arguments. More information here.
None of the above worked for me (tomcat 7.0.62)... As Sensei_Shoh notes see the class above the message and add this to logging.properties. My logs were:
Jan 18, 2016 8:44:21 PM org.apache.catalina.startup.TldConfig execute
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
so I added
org.apache.catalina.startup.TldConfig.level = FINE
in conf/logging.properties
After that I got so many "offending" files that I did not bother skipping them (and also reverted to normal logging...)
IMO, it's a clean way to achieve super.super.sayYourName()
behavior in Java.
public class GrandMa {
public void sayYourName(){
System.out.println("Grandma Fedora");
}
}
public class Mama extends GrandMa {
public void sayYourName(boolean lie){
if(lie){
super.sayYourName();
}else {
System.out.println("Mama Stephanida");
}
}
}
public class Daughter extends Mama {
public void sayYourName(boolean lie){
if(lie){
super.sayYourName(lie);
}else {
System.out.println("Little girl Masha");
}
}
}
public class TestDaughter {
public static void main(String[] args){
Daughter d = new Daughter();
System.out.print("Request to lie: d.sayYourName(true) returns ");
d.sayYourName(true);
System.out.print("Request not to lie: d.sayYourName(false) returns ");
d.sayYourName(false);
}
}
Output:
Request to lie: d.sayYourName(true) returns Grandma Fedora
Request not to lie: d.sayYourName(false) returns Little girl Masha
If you have just a couple of shared preferences to clear, then this solution is much nicer.
@Override
protected void setUp() throws Exception {
super.setUp();
Instrumentation instrumentation = getInstrumentation();
SharedPreferences preferences = instrumentation.getTargetContext().getSharedPreferences(...), Context.MODE_PRIVATE);
preferences.edit().clear().commit();
solo = new Solo(instrumentation, getActivity());
}
I would just add that no even number (bar 2) can be a prime number. This results in another condition prior to for loop. So the end code should look like this:
int IsPrime(unsigned int number) {
if (number <= 1) return 0; // zero and one are not prime
if ((number > 2) && ((number % 2) == 0)) return 0; //no even number is prime number (bar 2)
unsigned int i;
for (i=2; i*i<=number; i++) {
if (number % i == 0) return 0;
}
return 1;
}
Since no one yet mentioned this, in one particular case:
OLD_FILES=`echo *`
... create new files ...
rm -r $OLD_FILES
(or just rm $OLD_FILES
)
or
OLD_FILES=`ls *`
... create new files ...
rm -r $OLD_FILES
You may need to use shopt -s nullglob
if some files may be either there or not there:
SET_OLD_NULLGLOB=`shopt -p nullglob`
shopt -s nullglob
FILES=`echo *.sh *.bash`
$SET_OLD_NULLGLOB
without nullglob, echo *.sh *.bash
may give you "a.sh b.sh *.bash".
(Having said all that, I myself prefer this answer, even though it does not work in OSX)
You could fill the dependend cell (D2) by a User Defined Function (VBA Macro Function) that takes the value of the C2-Cell as input parameter, returning the current date as ouput.
Having C2 as input parameter for the UDF in D2 tells Excel that it needs to reevaluate D2 everytime C2 changes (that is if auto-calculation of formulas is turned on for the workbook).
EDIT:
Here is some code:
For the UDF:
Public Function UDF_Date(ByVal data) As Date
UDF_Date = Now()
End Function
As Formula in D2:
=UDF_Date(C2)
You will have to give the D2-Cell a Date-Time Format, or it will show a numeric representation of the date-value.
And you can expand the formula over the desired range by draging it if you keep the C2 reference in the D2-formula relative.
Note: This still might not be the ideal solution because every time Excel recalculates the workbook the date in D2 will be reset to the current value. To make D2 only reflect the last time C2 was changed there would have to be some kind of tracking of the past value(s) of C2. This could for example be implemented in the UDF by providing also the address alonside the value of the input parameter, storing the input parameters in a hidden sheet, and comparing them with the previous values everytime the UDF gets called.
Addendum:
Here is a sample implementation of an UDF that tracks the changes of the cell values and returns the date-time when the last changes was detected. When using it, please be aware that:
The usage of the UDF is the same as described above.
The UDF works only for single cell input ranges.
The cell values are tracked by storing the last value of cell and the date-time when the change was detected in the document properties of the workbook. If the formula is used over large datasets the size of the file might increase considerably as for every cell that is tracked by the formula the storage requirements increase (last value of cell + date of last change.) Also, maybe Excel is not capable of handling very large amounts of document properties and the code might brake at a certain point.
If the name of a worksheet is changed all the tracking information of the therein contained cells is lost.
The code might brake for cell-values for which conversion to string is non-deterministic.
The code below is not tested and should be regarded only as proof of concept. Use it at your own risk.
Public Function UDF_Date(ByVal inData As Range) As Date
Dim wb As Workbook
Dim dProps As DocumentProperties
Dim pValue As DocumentProperty
Dim pDate As DocumentProperty
Dim sName As String
Dim sNameDate As String
Dim bDate As Boolean
Dim bValue As Boolean
Dim bChanged As Boolean
bDate = True
bValue = True
bChanged = False
Dim sVal As String
Dim dDate As Date
sName = inData.Address & "_" & inData.Worksheet.Name
sNameDate = sName & "_dat"
sVal = CStr(inData.Value)
dDate = Now()
Set wb = inData.Worksheet.Parent
Set dProps = wb.CustomDocumentProperties
On Error Resume Next
Set pValue = dProps.Item(sName)
If Err.Number <> 0 Then
bValue = False
Err.Clear
End If
On Error GoTo 0
If Not bValue Then
bChanged = True
Set pValue = dProps.Add(sName, False, msoPropertyTypeString, sVal)
Else
bChanged = pValue.Value <> sVal
If bChanged Then
pValue.Value = sVal
End If
End If
On Error Resume Next
Set pDate = dProps.Item(sNameDate)
If Err.Number <> 0 Then
bDate = False
Err.Clear
End If
On Error GoTo 0
If Not bDate Then
Set pDate = dProps.Add(sNameDate, False, msoPropertyTypeDate, dDate)
End If
If bChanged Then
pDate.Value = dDate
Else
dDate = pDate.Value
End If
UDF_Date = dDate
End Function
Make the insertion of the date conditional upon the range.
This has an advantage of not changing the dates unless the content of the cell is changed, and it is in the range C2:C2, even if the sheet is closed and saved, it doesn't recalculate unless the adjacent cell changes.
Adapted from this tip and @Paul S answer
Private Sub Worksheet_Change(ByVal Target As Range)
Dim R1 As Range
Dim R2 As Range
Dim InRange As Boolean
Set R1 = Range(Target.Address)
Set R2 = Range("C2:C20")
Set InterSectRange = Application.Intersect(R1, R2)
InRange = Not InterSectRange Is Nothing
Set InterSectRange = Nothing
If InRange = True Then
R1.Offset(0, 1).Value = Now()
End If
Set R1 = Nothing
Set R2 = Nothing
End Sub
range = 10..50
rand(range)
or
range.to_a.sample
or
range.to_a.shuffle(this will shuffle whole array and you can pick a random number by first or last or any from this array to pick random one)
You can create an extension method for HtmlHelper to simplify the code in your CSHTML file. You could replace your tags with a method like this:
// Sample usage in CSHTML
@Html.ActionImage("Edit", new { id = MyId }, "~/Content/Images/Image.bmp", "Edit")
Here is a sample extension method for the code above:
// Extension method
public static MvcHtmlString ActionImage(this HtmlHelper html, string action, object routeValues, string imagePath, string alt)
{
var url = new UrlHelper(html.ViewContext.RequestContext);
// build the <img> tag
var imgBuilder = new TagBuilder("img");
imgBuilder.MergeAttribute("src", url.Content(imagePath));
imgBuilder.MergeAttribute("alt", alt);
string imgHtml = imgBuilder.ToString(TagRenderMode.SelfClosing);
// build the <a> tag
var anchorBuilder = new TagBuilder("a");
anchorBuilder.MergeAttribute("href", url.Action(action, routeValues));
anchorBuilder.InnerHtml = imgHtml; // include the <img> tag inside
string anchorHtml = anchorBuilder.ToString(TagRenderMode.Normal);
return MvcHtmlString.Create(anchorHtml);
}
There are several mechanisms to avoid a link to reach its destination. The one from the question is not much intuitive.
A cleaner option is to use href="#no"
where #no
is a non-defined anchor in the document.
You can use a more semantic name such as #disable, or #action to increase readability.
Benefits of the approach:
Drawbacks:
Since the <a>
element is not acting as a link, the best option in these cases is not using an <a>
element but a <div>
and provide the desired link-like style.
This is quite useful question. I think that my solution on Windows 10 PHP7 is rather useful for people who have yet some UTF-8 conversion trouble.
Here are my steps. The PHP script calling the following function, here named utfsave.php must have UTF-8 encoding itself, this can be easily done by conversion on UltraEdit.
In utfsave.php, we define a function calling PHP fopen($filename, "wb"), ie, it's opened in both w write mode, and especially with b in binary mode.
<?php
//
// UTF-8 ??:
//
// fnc001: save string as a file in UTF-8:
// The resulting file is UTF-8 only if $strContent is,
// with French accents, chinese ideograms, etc..
//
function entSaveAsUtf8($strContent, $filename) {
$fp = fopen($filename, "wb");
fwrite($fp, $strContent);
fclose($fp);
return True;
}
//
// 0. write UTF-8 string in fly into UTF-8 file:
//
$strContent = "My string contains UTF-8 chars ie ???? for un Γ©tΓ© en France";
$filename = "utf8text.txt";
entSaveAsUtf8($strContent, $filename);
//
// 2. convert CP936 ANSI/OEM - chinese simplified GBK file into UTF-8 file:
//
$strContent = file_get_contents("cp936gbktext.txt");
$strContent = mb_convert_encoding($strContent, "UTF-8", "CP936");
$filename = "utf8text2.txt";
entSaveAsUtf8($strContent, $filename);
?>
The source file cp936gbktext.txt file content:
>>Get-Content cp936gbktext.txt
My string contains UTF-8 chars ie ???? for un Γ©tΓ© en France 936 (ANSI/OEM - chinois simplifiΓ© GBK)
Running utf8save.php on Windows 10 PHP, thus created utf8text.txt, utf8text2.txt files will be automatically saved in UTF-8 format.
With this method, BOM char is not required. BOM solution is bad because it causes troubles when we do sourcing an sql file for MySQL for example.
It's worth noting that I failed making work file_put_contents($filename, utf8_encode($mystring)); for this purpose.
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
If you don't know the encoding of the source file, you can list encodings with PHP:
print_r(mb_list_encodings());
This gives a list like this:
Array
(
[0] => pass
[1] => wchar
[2] => byte2be
[3] => byte2le
[4] => byte4be
[5] => byte4le
[6] => BASE64
[7] => UUENCODE
[8] => HTML-ENTITIES
[9] => Quoted-Printable
[10] => 7bit
[11] => 8bit
[12] => UCS-4
[13] => UCS-4BE
[14] => UCS-4LE
[15] => UCS-2
[16] => UCS-2BE
[17] => UCS-2LE
[18] => UTF-32
[19] => UTF-32BE
[20] => UTF-32LE
[21] => UTF-16
[22] => UTF-16BE
[23] => UTF-16LE
[24] => UTF-8
[25] => UTF-7
[26] => UTF7-IMAP
[27] => ASCII
[28] => EUC-JP
[29] => SJIS
[30] => eucJP-win
[31] => EUC-JP-2004
[32] => SJIS-win
[33] => SJIS-Mobile#DOCOMO
[34] => SJIS-Mobile#KDDI
[35] => SJIS-Mobile#SOFTBANK
[36] => SJIS-mac
[37] => SJIS-2004
[38] => UTF-8-Mobile#DOCOMO
[39] => UTF-8-Mobile#KDDI-A
[40] => UTF-8-Mobile#KDDI-B
[41] => UTF-8-Mobile#SOFTBANK
[42] => CP932
[43] => CP51932
[44] => JIS
[45] => ISO-2022-JP
[46] => ISO-2022-JP-MS
[47] => GB18030
[48] => Windows-1252
[49] => Windows-1254
[50] => ISO-8859-1
[51] => ISO-8859-2
[52] => ISO-8859-3
[53] => ISO-8859-4
[54] => ISO-8859-5
[55] => ISO-8859-6
[56] => ISO-8859-7
[57] => ISO-8859-8
[58] => ISO-8859-9
[59] => ISO-8859-10
[60] => ISO-8859-13
[61] => ISO-8859-14
[62] => ISO-8859-15
[63] => ISO-8859-16
[64] => EUC-CN
[65] => CP936
[66] => HZ
[67] => EUC-TW
[68] => BIG-5
[69] => CP950
[70] => EUC-KR
[71] => UHC
[72] => ISO-2022-KR
[73] => Windows-1251
[74] => CP866
[75] => KOI8-R
[76] => KOI8-U
[77] => ArmSCII-8
[78] => CP850
[79] => JIS-ms
[80] => ISO-2022-JP-2004
[81] => ISO-2022-JP-MOBILE#KDDI
[82] => CP50220
[83] => CP50220raw
[84] => CP50221
[85] => CP50222
)
If you cannot guess, you try one by one, as mb_detect_encoding() cannot do the job easily.
if it is a RSA key
openssl rsa -pubout -in my_rsa_key.pem
if you need it in a format for openssh , please see Use RSA private key to generate public key?
Note that public key is generated from the private key and ssh uses the identity file (private key file) to generate and send public key to server and un-encrypt the encrypted token from the server via the private key in identity file.
Regular javascript can be used to trap the backspace key. You can use the event.keyCode method. The keycode is 8, so the code would look something like this:
if (event.keyCode == 8) {
// Do stuff...
}
If you want to check for both the [delete] (46) as well as the [backspace] (8) keys, use the following:
if (event.keyCode == 8 || event.keyCode == 46) {
// Do stuff...
}
really like keep things simple like this :)
$('input[type=file]').wrap('<form></form>').parent().trigger('reset').children().unwrap('<form></form>');
I think that library does not mentioned:
github url:
https://github.com/jfeinstein10/SlidingMenu
The best solution is using DATE() function and extracting yy, mm, and dd from the string with RIGHT(), MID() and LEFT() functions, the final will be some DATE(LEFT(),MID(),RIGHT()), details here
do you mean something like pgAdmin for administration?
When using -c
command, as a tricky way, instead of reading the stdin
(and more flexible in some cases) you can pass a shell script command as well to your python command by putting the shell command in quotes within a parenthesis started by $
sign.
e.g.
python3 -c "import sys; print(len(sys.argv[1].split('\n')))" "$(cat ~/.goldendict/history)"
This will count the number of lines from goldendict's history file.
String text = "text";
text += new String(" ");
This will update all the rows in that columns if safe mode is not enabled.
UPDATE table SET columnB = columnA;
If safe mode is enabled then you will need to use a where clause. I use primary key as greater than 0 basically all will be updated
UPDATE table SET columnB = columnA where table.column>0;
You can easily present Html.ActionLink as a button by using the appropriate CSS style. For example:
@Html.ActionLink("Save", "ActionMethod", "Controller", new { @class = "btn btn-primary" })
Some of the following was gleaned off of this site. This is what I did to duplicate a record in a table with any number of fields:
This also assumes you have an AI field at the beginning of the table
function duplicateRow( $id = 1 ){
dbLink();//my db connection
$qColumnNames = mysql_query("SHOW COLUMNS FROM table") or die("mysql error");
$numColumns = mysql_num_rows($qColumnNames);
for ($x = 0;$x < $numColumns;$x++){
$colname[] = mysql_fetch_row($qColumnNames);
}
$sql = "SELECT * FROM table WHERE tableId = '$id'";
$row = mysql_fetch_row(mysql_query($sql));
$sql = "INSERT INTO table SET ";
for($i=1;$i<count($colname)-4;$i++){//i set to 1 to preclude the id field
//we set count($colname)-4 to avoid the last 4 fields (good for our implementation)
$sql .= "`".$colname[$i][0]."` = '".$row[$i]. "', ";
}
$sql .= " CreateTime = NOW()";// we need the new record to have a new timestamp
mysql_query($sql);
$sql = "SELECT MAX(tableId) FROM table";
$res = mysql_query($sql);
$row = mysql_fetch_row($res);
return $row[0];//gives the new ID from auto incrementing
}
Not certain what the HTML looks like (that would help with answers). If it's
<div class="testimonials content">stuff</div>
then simply remove the space in your css. A la...
.testimonials.content { css here }
UPDATE:
Okay, after seeing HTML see if this works...
.testimonials .wrapper .content { css here }
or just
.testimonials .wrapper { css here }
or
.desc-container .wrapper { css here }
all 3 should work.
Jason Scheirer's answer is correct but could use some more exposition.
First off, to repeat a string an integer number of times, you can use overloaded multiplication:
>>> 'abc' * 7
'abcabcabcabcabcabcabc'
So, to repeat a string until it's at least as long as the length you want, you calculate the appropriate number of repeats and put it on the right-hand side of that multiplication operator:
def repeat_to_at_least_length(s, wanted):
return s * (wanted//len(s) + 1)
>>> repeat_to_at_least_length('abc', 7)
'abcabcabc'
Then, you can trim it to the exact length you want with an array slice:
def repeat_to_length(s, wanted):
return (s * (wanted//len(s) + 1))[:wanted]
>>> repeat_to_length('abc', 7)
'abcabca'
Alternatively, as suggested in pillmod's answer that probably nobody scrolls down far enough to notice anymore, you can use divmod
to compute the number of full repetitions needed, and the number of extra characters, all at once:
def pillmod_repeat_to_length(s, wanted):
a, b = divmod(wanted, len(s))
return s * a + s[:b]
Which is better? Let's benchmark it:
>>> import timeit
>>> timeit.repeat('scheirer_repeat_to_length("abcdefg", 129)', globals=globals())
[0.3964178159367293, 0.32557755894958973, 0.32851039397064596]
>>> timeit.repeat('pillmod_repeat_to_length("abcdefg", 129)', globals=globals())
[0.5276265419088304, 0.46511475392617285, 0.46291469305288047]
So, pillmod's version is something like 40% slower, which is too bad, since personally I think it's much more readable. There are several possible reasons for this, starting with its compiling to about 40% more bytecode instructions.
Note: these examples use the new-ish //
operator for truncating integer division. This is often called a Python 3 feature, but according to PEP 238, it was introduced all the way back in Python 2.2. You only have to use it in Python 3 (or in modules that have from __future__ import division
) but you can use it regardless.
I wrote a different approach to debug Node.js code which is stable and is extremely simple. It is available at https://github.com/s-a/iron-node.
An opensource cross-platform visual debugger.
Installation:
npm install iron-node -g;
Debug:
iron-node yourscript.js;
Use this overload (RenderPartialExtensions.RenderPartial
on MSDN):
public static void RenderPartial(
this HtmlHelper htmlHelper,
string partialViewName,
Object model
)
so:
@{Html.RenderPartial(
"FullName",
new { firstName = model.FirstName, lastName = model.LastName});
}
I had this problem while inheriting from ApiController instead of the regular Controller class. I solved it by using var container = Request.GetQueryNameValuePairs().ToLookup(x => x.Key, x => x.Value);
I followed this thread How to get Request Querystring values?
EDIT: After trying to filter through the container I was getting odd error messages. After going to my project properties and I unchecked the Optimize Code checkbox which changed so that all of a sudden the parameters in my controller where filled up from the url as I wanted.
Hopefully this will help someone with the same problem..
I don't realize why MimeTypeMap.getFileExtensionFromUrl()
has problems with space
s and some other characters, that returns ""
, but I just wrote this method to change the file name to an admit-able one. It's just playing with String
s. However, It kind of works. Through the method, the space
s existing in the file name is turned into a desirable character (which, here, is "x") via replaceAll(" ", "x")
and other unsuitable characters are turned into a suitable one via URLEncoder
. so the usage (according to the codes presented in the question and the selected answer) should be something like getMimeType(reviseUrl(url))
.
private String reviseUrl(String url) {
String revisedUrl = "";
int fileNameBeginning = url.lastIndexOf("/");
int fileNameEnding = url.lastIndexOf(".");
String cutFileNameFromUrl = url.substring(fileNameBeginning + 1, fileNameEnding).replaceAll(" ", "x");
revisedUrl = url.
substring(0, fileNameBeginning + 1) +
java.net.URLEncoder.encode(cutFileNameFromUrl) +
url.substring(fileNameEnding, url.length());
return revisedUrl;
}
You're probably mistaking what PHP.ini you need to edit. first, add a PHPinfo(); to a info.php, and run it from your browser.
Write down the PHP ini directory path you see in the variables list now! You will probably notice that it's different from your PHP-CLI ini file.
Enable the extension
You're done :-)
Edit package.json
:
...
"engines": {
"node": "5.0.0",
"npm": "4.6.1"
},
...
and Server.js
:
...
var port = process.env.PORT || 3000;
app.listen(port, "0.0.0.0", function() {
console.log("Listening on Port 3000");
});
...
I wanted the AJAX loaded content removed when the modal closed, so I adjusted the line suggested by others (coffeescript syntax):
$('#my-modal').on 'hidden.bs.modal', (event) ->
$(this).removeData('bs.modal').children().remove()
You will have to use vendor prefixes to support different browsers and therefore can't use it in shorthand.
body {
Β Β Β Β background: url(images/bg.jpg) no-repeat center center fixed;
Β Β Β Β -webkit-background-size: cover;
Β Β Β Β -moz-background-size: cover;
Β Β Β Β -o-background-size: cover;
Β Β Β Β background-size: cover;
}
driver.Manage().Window.Maximize();
The page.github.com does mention:
Github Pages are hosted free and easily published through our site,
Without ever mentioning access control.
The GitHub page help doesn't mention any ACL either.
They are best managed in a gh-pages branch, and can be managed in their own submodule.
But again, without any restriction in term of visibility once published by GitHub.
In .Net core 3.1 you can try like this
d?.value2 , d?.value3
I have a sample
import * as types from '../../helpers/ActionTypes';
var initialState = {
changedValues: {}
};
const quickEdit = (state = initialState, action) => {
switch (action.type) {
case types.PRODUCT_QUICKEDIT:
{
const item = action.item;
const changedValues = {
...state.changedValues,
[item.id]: item,
};
return {
...state,
loading: true,
changedValues: changedValues,
};
}
default:
{
return state;
}
}
};
export default quickEdit;
li {
padding-left: 30px;
}
_x000D_
<p>Some text to show left edge of container.<p>
<ul>
<li>List item</li>
</ul>
_x000D_
li {
margin-left: 30px;
}
_x000D_
<p>Some text to show left edge of container.<p>
<ul>
<li>List item</li>
</ul>
_x000D_
There should be a binary called "pip2.7" installed at some location included within your $PATH variable.
You can find that out by typing
which pip2.7
This should print something like '/usr/local/bin/pip2.7' to your stdout. If it does not print anything like this, it is not installed. In that case, install it by running
$ wget https://bootstrap.pypa.io/get-pip.py
$ sudo python2.7 get-pip.py
Now, you should be all set, and
which pip2.7
should return the correct output.
If everything else fails, it's good to try my option and download a HAXM installer.
It needs to be copied to HAXM installation folder and then started from command line (start CMD as an Administrator). After restarting computer HAXM will be installed. It perfectly worked for me as I was having problems with installing it on my laptop.
After all simply type sc query
intelhaxm in your cmd in order to check whether HAXM is installed properly.
The easiest way that I have found is to set the activity's theme in the AndroidManifest to android:theme="@android:style/Theme.Holo.Dialog"
.
Then in the activity's onCreate method, call getWindow().setBackgroundDrawable(new ColorDrawable(0));
.
In your Request class (that extends Request), override the getParams() method. You would do the same for headers, just override getHeaders().
If you look at PostWithBody class in TestRequest.java in Volley tests, you'll find an example. It goes something like this
public class LoginRequest extends Request<String> {
// ... other methods go here
private Map<String, String> mParams;
public LoginRequest(String param1, String param2, Listener<String> listener, ErrorListener errorListener) {
super(Method.POST, "http://test.url", errorListener);
mListener = listener;
mParams = new HashMap<String, String>();
mParams.put("paramOne", param1);
mParams.put("paramTwo", param2);
}
@Override
public Map<String, String> getParams() {
return mParams;
}
}
Evan Charlton was kind enough to make a quick example project to show us how to use volley. https://github.com/evancharlton/folly/
run github that you downloaded, click tools and options symbol(top right), click about github for windows and then open the debug log. under DIAGNOSTICS look for Git Executable Exists:
Here is another solution (only relevant declarations listed):
.text span {
display:inline-block;
margin-right:100%;
}
When the margin is expressed in percentage, that percentage is taken from the width of the parent node, so 100% means as wide as the parent, which results in the next element getting "pushed" to a new line.
You can use Path.GetFileNameWithoutExtension
:
foreach (FileInfo fi in smFiles)
{
builder.Append(Path.GetFileNameWithoutExtension(fi.Name));
builder.Append(", ");
}
Although I am surprised there isn't a way to get this directly from the FileInfo
(or at least I can't see it).
mysql -u root -p;
And mysql will ask for the password
JPG does not support a transparent background, you can easily convert it to a PNG which does support a transparent background by opening it in near any photo editor and save it as a.PNG
normaly is better image store in public folder (because it has write permission already that you can use when I upload images to it)
public
upload_media
photos
image.png
$image = public_path() . '/upload_media/photos/image.png'; // destination path
view PHP
<img src="<?= $image ?>">
View blade
<img src="{{ $image }}">
The TextBox
has a property called ReadOnly
. If you set that property to true then the TextBox
will still be able to scroll but the user wont be able to change the value.
Just for the most popular linux Ubuntu
& it's bash
:
Check which shell are you using? Mostly below works, else see this:
echo $0
If above prints bash
, then below will work:
printf "hello with no new line printed at end"
OR
echo -n "hello with no new line printed at end"
Try to call your proc in this way:
DECLARE @UserIDout int
EXEC YOURPROC @EmailAddress = 'sdfds', @NickName = 'sdfdsfs', ..., @UserId = @UserIDout OUTPUT
SELECT @UserIDout
Applies to Oreo+ only...
I made an app with code here on GitHub which uses reflection and DexMaker to 'get at' Oreo's tethering functionality, which is now in ConnectionManager
, rather than WifiManager
.
The stuff in WifiManager
is good only for a closed wifi network (which explained the Closed bit in the class names!).
More explanation https://stackoverflow.com/a/49356255/772333.
For those who are using Visual Studio (2015 in my case)
Close your project in VS. Especially in big projects VS tends to freak out when merging using the UI.
Do the merge in command prompt.
git checkout target_branch
git merge source_branch
Then open the project in VS and go to Team Explorer -> Branch. Now there is a message that says Merge is pending and conflicting files are listed right below the message.
Click the conflicting file and you will have the option to Merge, Compare, Take Source, Take Target. The merge tool in VS is very easy to use.
Add following dll files to bin folder:
DotNetOpenAuth.AspNet.dll
DotNetOpenAuth.Core.dll
DotNetOpenAuth.OAuth.Consumer.dll
DotNetOpenAuth.OAuth.dll
DotNetOpenAuth.OpenId.dll
DotNetOpenAuth.OpenId.RelyingParty.dll
If you will not need them, delete dependentAssemblies
from config named 'DotNetOpenAuth.Core' etc..
Make sure you are using binding to get component props in REACT
class FileUploader extends Component {
constructor (props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
onChange=(e,props)=>{
const files = e.target.files;
const selectedFile = files[0];
ProcessFileUpload(selectedFile,props.ProgressCallBack,props.ErrorCallBack,props.CompleatedCallBack,props.BaseURL,props.Location,props.FilesAllowed);
}
handleClick = () => {
this.refs.fileUploader.click();
}
render()
{
return(
<div>
<button type="button" onClick={this.handleClick}>Select File</button>
<input type='file' onChange={(e)=>this.onChange(e,this.props)} ref="fileUploader" style={{display:"none"}} />
</div>)
}
}
This is an old question. CSS has evolved. There now is the vh
(viewport height) unit, also new layout options like flexbox
or CSS grid
to achieve classical designs in cleaner ways.
opened wamp/bin/apache/apache2.4.4/bin/php config.. wamp/bin/php/php5.4.16/php conf settings, php-ini production, php-ini dev, phpForApache find extension=php_openssl.dll and uncomment by removing ;
for /f "tokens=2-8 delims=.:/ " %%a in ("%date% %time: =0%") do set DateNtime=%%c-%%a-%%b_%%d-%%e-%%f.%%g
echo %DateNtime%
Or, from the command line:
for /f "tokens=2-8 delims=.:/ " %a in ("%date% %time: =0%") do echo %c-%a-%b_%d-%e-%f.%g
EDIT: As per bryce's non-standard time/date specs. (03-Sep-12 9:06:21.54
)
@echo off
setlocal enabledelayedexpansion
for /f "tokens=1-7 delims=.:/- " %%a in ("%date% %time%") do (
if "%%b"=="Jan" set MM=01
if "%%b"=="Feb" set MM=02
if "%%b"=="Mar" set MM=03
if "%%b"=="Apr" set MM=04
if "%%b"=="May" set MM=05
if "%%b"=="Jun" set MM=06
if "%%b"=="Jul" set MM=07
if "%%b"=="Aug" set MM=08
if "%%b"=="Sep" set MM=09
if "%%b"=="Oct" set MM=10
if "%%b"=="Nov" set MM=11
if "%%b"=="Dec" set MM=12
set HH=0%%d
set HH=!HH:~-2!
echo 20%%c-!MM!-%%a_!HH!-%%e-%%f.%%g
)
endlocal
Thanks to marc_s's answer I solved my original problem - inspired to take it a step further and post one approach to transforming a whole table at a time - tsql script to generate the alter column statements:
DECLARE @tableName VARCHAR(MAX)
SET @tableName = 'affiliate'
--EXEC sp_columns @tableName
SELECT 'Alter table ' + @tableName + ' alter column ' + col.name
+ CASE ( col.user_type_id )
WHEN 231
THEN ' nvarchar(' + CAST(col.max_length / 2 AS VARCHAR) + ') '
END + 'collate Latin1_General_CI_AS ' + CASE ( col.is_nullable )
WHEN 0 THEN ' not null'
WHEN 1 THEN ' null'
END
FROM sys.columns col
WHERE object_id = OBJECT_ID(@tableName)
gets: ALTER TABLE Affiliate ALTER COLUMN myTable NVARCHAR(4000) COLLATE Latin1_General_CI_AS NOT NULL
I'll admit to being puzzled by the need to col.max_length / 2 -
While disabling all "touchmove" events might seem like a good idea, as soon as you need other scrollable elements on the page it will cause problems. On top of that, if you only disable "touchmove" events on certain elements (e.g. body if you want the page to be non-scrollable), as soon as it is enabled anywhere else, IOS will cause unstoppable propagation in Chrome when the URL bar toggles.
While I cannot explain this behavior, it looks like the only way to prevent seems to set the body's position to fixed
. The only problem doing is that you will lose the position of the document - this is especially annoying in modals for example. One way to solve it would be to use these simple VanillaJS functions:
function disableDocumentScrolling() {
if (document.documentElement.style.position != 'fixed') {
// Get the top vertical offset.
var topVerticalOffset = (typeof window.pageYOffset != 'undefined') ?
window.pageYOffset : (document.documentElement.scrollTop ?
document.documentElement.scrollTop : 0);
// Set the document to fixed position (this is the only way around IOS' overscroll "feature").
document.documentElement.style.position = 'fixed';
// Set back the offset position by user negative margin on the fixed document.
document.documentElement.style.marginTop = '-' + topVerticalOffset + 'px';
}
}
function enableDocumentScrolling() {
if (document.documentElement.style.position == 'fixed') {
// Remove the fixed position on the document.
document.documentElement.style.position = null;
// Calculate back the original position of the non-fixed document.
var scrollPosition = -1 * parseFloat(document.documentElement.style.marginTop);
// Remove fixed document negative margin.
document.documentElement.style.marginTop = null;
// Scroll to the original position of the non-fixed document.
window.scrollTo(0, scrollPosition);
}
}
Using this solution you can have a fixed document and any other element in your page can overflow by using simple CSS (e.g., overflow: scroll;
). No need for special classes or anything else.
This simple formula should work.
Give the element whose text will contain a tab the following CSS property:
white-space:pre
.
Otherwise your html may not render tabs at all. Then, wherever you want to have a tab in your text, type 	
.
Since you didn't mention CSS, if you want to do this without a CSS file, just use
<tag-name style="white-space:pre">text in element	more text</tag-name>
in your HTML.
I had to use the install
function instead:
conda install pandas=0.13.1
You should be careful about using the finally block, as it is not the same thing as using an else block in the try, except. The finally block will be run regardless of the outcome of the try except.
In [10]: dict_ = {"a": 1}
In [11]: try:
....: dict_["b"]
....: except KeyError:
....: pass
....: finally:
....: print "something"
....:
something
As everyone has noted using the else block causes your code to be more readable, and only runs when an exception is not thrown
In [14]: try:
dict_["b"]
except KeyError:
pass
else:
print "something"
....:
call super.myMethod();
Using POST
function DoAction( id, name )
{
$.ajax({
type: "POST",
url: "someurl.php",
data: "id=" + id + "&name=" + name,
success: function(msg){
alert( "Data Saved: " + msg );
}
});
}
Using GET
function DoAction( id, name )
{
$.ajax({
type: "GET",
url: "someurl.php",
data: "id=" + id + "&name=" + name,
success: function(msg){
alert( "Data Saved: " + msg );
}
});
}
EDIT:
A, perhaps, better way to do this that would work (using GET) if javascript were not enabled would be to generate the URL for the href, then use a click handler to call that URL via ajax instead.
<a href="/someurl.php?id=1&name=Jose" class="ajax-link"> Click </a>
<a href="/someurl.php?id=2&name=Juan" class="ajax-link"> Click </a>
<a href="/someurl.php?id=3&name=Pedro" class="ajax-link"> Click </a>
...
<a href="/someurl.php?id=n&name=xxx" class="ajax-link"> Click </a>
<script type="text/javascript">
$(function() {
$('.ajax-link').click( function() {
$.get( $(this).attr('href'), function(msg) {
alert( "Data Saved: " + msg );
});
return false; // don't follow the link!
});
});
</script>
In order to get rgba integer value instead of float value, we can do
rgba = cmap(0.5,bytes=True)
So to simplify the code based on answer from Ffisegydd, the code would be like this:
#import colormap
from matplotlib import cm
#normalize item number values to colormap
norm = matplotlib.colors.Normalize(vmin=0, vmax=1000)
#colormap possible values = viridis, jet, spectral
rgba_color = cm.jet(norm(400),bytes=True)
#400 is one of value between 0 and 1000
Make sure that all these are in upto date.
Here an example that I used in my TubeCount app.
I also use the fields parameter to filter the JSON result, so only the fields that I need are returned.
var fields = "fields=openSearch:totalResults,entry(title,media:group(yt:videoid),media:group(yt:duration),media:group(media:description),media:group(media:thumbnail[@yt:name='default'](@url)),yt:statistics,yt:rating,published,gd:comments(gd:feedLink(@countHint)))";
var channel = "wiibart";
$.ajax({
url: "http://gdata.youtube.com/feeds/api/users/"+channel+"/uploads?"+fields+"&v=2&alt=json",
success: function(data){
var len = data.feed.entry.length;
for(var k =0; k<len; k++){
var yt = data.feed.entry[k];
v.count = Number(yt.yt$statistics != undefined && yt.yt$statistics.viewCount != undefined ? yt.yt$statistics.viewCount : 0);
}
}
});
Afaik the Browser application data is NOT clearable for other apps, since it is store in private_mode
. So executing this command could probalby only work on rooted devices. Otherwise you should try another approach.
By default, rails server uses port 3000.
So, you have 2 options to run rails server.
1. Either you can run the server on other port by defining custom port using the following command
rails s -p 3001
2. Or you can kill all the running ruby process by running following command
killall -9 ruby
then run rails server
Even once you fixed the mis-cased if
and improper indentation in your code, it wouldn't work as you probably expected. To check a string against a set of strings, use in
. Here's how you'd do it (and note that if
is all lowercase and that the code within the if
block is indented one level).
One approach:
if answer in ['y', 'Y', 'yes', 'Yes', 'YES']:
print("this will do the calculation")
Another:
if answer.lower() in ['y', 'yes']:
print("this will do the calculation")
XmlDocument.Attributes
perhaps? (Which has a method GetNamedItem that will presumably do what you want, although I've always just iterated the attribute collection)
The #import directive was added to Objective-C as an improved version of #include. Whether or not it's improved, however, is still a matter of debate. #import ensures that a file is only ever included once so that you never have a problem with recursive includes. However, most decent header files protect themselves against this anyway, so it's not really that much of a benefit.
Basically, it's up to you to decide which you want to use. I tend to #import headers for Objective-C things (like class definitions and such) and #include standard C stuff that I need. For example, one of my source files might look like this:
#import <Foundation/Foundation.h>
#include <asl.h>
#include <mach/mach.h>
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
cal.set(year, month, date);
SimpleDateFormat format1 = new SimpleDateFormat("yyyy MM dd");
String formatted = format1.format(cal.getTime());
System.out.println(formatted);
}
This will take care of the empty td:
<td style="min-width: 20px;"></td>
Use any method described in the previous post to somehow catch the mysql error.
Most common is:
$res = mysql_query('bla');
if ($res===false) {
//error
die();
}
//normal page
This would also work:
function error() {
//error
die()
}
$res = mysql_query('bla') or error();
//normal page
try { ... } catch {Exception $e) { .... }
will not work!
Note: Not directly related to you question but I think it would much more better if you display something usefull to the user. I would never revisit a website that just displays a blank screen or any mysterious error message.
If you want to add style in all child and no specification for html tag then use it.
Parent tag div.parent
child tag inside the div.parent like <a>
, <input>
, <label>
etc.
code : div.parent * {color: #045123!important;}
You can also remove important, its not required
None of the above worked on Sublime Text 3 on Windows 10, Ctrl + Shift + ' with the Emmet Sublime Text 3 plugin works great and was the only working solution for me. Ctrl + Shift + T re-opens the last closed item and to my knowledge of Sublime, has done so since early builds of ST3 or late builds of ST2.
I solve a similar problem.
http://<Mac ip>:<your customer server port>
in iPhone's safari Swift4 Code
Try this some new extension methods:
import UIKit
extension UIView {
fileprivate struct AssociatedObjectKeys {
static var tapGestureRecognizer = "MediaViewerAssociatedObjectKey_mediaViewer"
}
fileprivate typealias Action = (() -> Void)?
fileprivate var tapGestureRecognizerAction: Action? {
set {
if let newValue = newValue {
// Computed properties get stored as associated objects
objc_setAssociatedObject(self, &AssociatedObjectKeys.tapGestureRecognizer, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
}
get {
let tapGestureRecognizerActionInstance = objc_getAssociatedObject(self, &AssociatedObjectKeys.tapGestureRecognizer) as? Action
return tapGestureRecognizerActionInstance
}
}
public func addTapGestureRecognizer(action: (() -> Void)?) {
self.isUserInteractionEnabled = true
self.tapGestureRecognizerAction = action
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTapGesture))
self.addGestureRecognizer(tapGestureRecognizer)
}
@objc fileprivate func handleTapGesture(sender: UITapGestureRecognizer) {
if let action = self.tapGestureRecognizerAction {
action?()
} else {
print("no action")
}
}
}
Now whenever we want to add a UITapGestureRecognizer
to a UIView
or UIView
subclass like UIImageView
, we can do so without creating associated functions for selectors!
Usage:
profile_ImageView.addTapGestureRecognizer {
print("image tapped")
}
Its supported in notepad++ 5.0+ but not enabled by default. You can enable it from settings -> preferences
This is how you get unique from an array with two or more properties. The sort is vital and the key to getting it to work correctly. Otherwise you just get one item returned.
PowerShell Script:
$objects = @(
[PSCustomObject] @{ Message = "1"; MachineName = "1" }
[PSCustomObject] @{ Message = "2"; MachineName = "1" }
[PSCustomObject] @{ Message = "3"; MachineName = "1" }
[PSCustomObject] @{ Message = "4"; MachineName = "1" }
[PSCustomObject] @{ Message = "5"; MachineName = "1" }
[PSCustomObject] @{ Message = "1"; MachineName = "2" }
[PSCustomObject] @{ Message = "2"; MachineName = "2" }
[PSCustomObject] @{ Message = "3"; MachineName = "2" }
[PSCustomObject] @{ Message = "4"; MachineName = "2" }
[PSCustomObject] @{ Message = "5"; MachineName = "2" }
[PSCustomObject] @{ Message = "1"; MachineName = "1" }
[PSCustomObject] @{ Message = "2"; MachineName = "1" }
[PSCustomObject] @{ Message = "3"; MachineName = "1" }
[PSCustomObject] @{ Message = "4"; MachineName = "1" }
[PSCustomObject] @{ Message = "5"; MachineName = "1" }
[PSCustomObject] @{ Message = "1"; MachineName = "2" }
[PSCustomObject] @{ Message = "2"; MachineName = "2" }
[PSCustomObject] @{ Message = "3"; MachineName = "2" }
[PSCustomObject] @{ Message = "4"; MachineName = "2" }
[PSCustomObject] @{ Message = "5"; MachineName = "2" }
)
Write-Host "Sorted on both properties with -Unique" -ForegroundColor Yellow
$objects | Sort-Object -Property Message,MachineName -Unique | Out-Host
Write-Host "Sorted on just Message with -Unique" -ForegroundColor Yellow
$objects | Sort-Object -Property Message -Unique | Out-Host
Write-Host "Sorted on just MachineName with -Unique" -ForegroundColor Yellow
$objects | Sort-Object -Property MachineName -Unique | Out-Host
Output:
Sorted on both properties with -Unique
Message MachineName
------- -----------
1 1
1 2
2 1
2 2
3 1
3 2
4 1
4 2
5 1
5 2
Sorted on just Message with -Unique
Message MachineName
------- -----------
1 1
2 1
3 1
4 1
5 2
Sorted on just MachineName with -Unique
Message MachineName
------- -----------
1 1
3 2
Source: https://powershell.org/forums/topic/need-to-unique-based-on-multiple-properties/
to get domain/hostname and Origin*
url = 'https://stackoverflow.com/questions/9626535/get-protocol-host-name-from-url'
hostname = url.split('/')[2] # stackoverflow.com
origin = '/'.join(url.split('/')[:3]) # https://stackoverflow.com
*Origin
is used in XMLHttpRequest
headers
I also saw this change on my Mac when I went from running pip
to sudo pip
. Adding -H
to sudo causes the message to go away for me. E.g.
sudo -H pip install foo
man sudo
tells me that -H
causes sudo
to set $HOME
to the target users (root in this case).
So it appears pip is looking into $HOME/Library/Log
and sudo
by default isn't setting $HOME
to /root/
. Not surprisingly ~/Library/Log
is owned by you as a user rather than root.
I suspect this is some recent change in pip. I'll run it with sudo -H
for now to work around.
The server at x3.chatforyoursite.com
needs to output the following header:
Access-Control-Allow-Origin: http://www.example.com
Where http://www.example.com
is your website address. You should check your settings on chatforyoursite.com
to see if you can enable this - if not their technical support would probably be the best way to resolve this. However to answer your question, you need the remote site to allow your site to access AJAX responses client side.
It's because you're trying to assign an object by reference. Remove the ampersand and your script should work as intended.
You can query the data dictionary/catalog views to find out when an object was created as well as the time of last DDL involving the object (example: alter table)
select *
from all_objects
where owner = '<name of schema owner>'
and object_name = '<name of table>'
The column "CREATED" tells you when the object was created. The column "LAST_DDL_TIME" tells you when the last DDL was performed against the object.
As for when a particular row was inserted/updated, you can use audit columns like an "insert_timestamp" column or use a trigger and populate an audit table
Decorate the model property with the DisplayName attribute.
You can specify JsonSerializerSettings
for each JsonConvert
, and you can set a global default.
Single JsonConvert
with an overload:
// Option #1.
JsonSerializerSettings config = new JsonSerializerSettings { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore };
this.json = JsonConvert.SerializeObject(YourObject, Formatting.Indented, config);
// Option #2 (inline).
JsonConvert.SerializeObject(YourObject, Formatting.Indented,
new JsonSerializerSettings() {
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
}
);
Global Setting with code in Application_Start()
in Global.asax.cs:
JsonConvert.DefaultSettings = () => new JsonSerializerSettings {
Formatting = Newtonsoft.Json.Formatting.Indented,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
};
Reference: https://github.com/JamesNK/Newtonsoft.Json/issues/78
It is fairly risky to rely on javascript functions to compare and play with numbers. In javascript (0.1+0.2 == 0.3) will return false due to rounding errors. Use the math.js library.
For this, I prefer to keep a correct HTML semantic, and to use a CSS simple as possible.
Something like this would do the job :
label{
display: block;
float: left;
width : 120px;
}
One drawback however : you might have to pick the right label width for each form, and this is not easy if your labels can be dynamic (I18N labels for instance).
You can get a shorter version by using sys.path[0]
.
os.chdir(sys.path[0])
From http://docs.python.org/library/sys.html#sys.path
As initialized upon program startup, the first item of this list,
path[0]
, is the directory containing the script that was used to invoke the Python interpreter
If you want more control over how the conversion takes place, you can use ConvertAll:
var stringList = myList.ConvertAll(obj => obj.SomeToStringMethod());
i have created a pre build script for the same problem because i need some differents api endpoints for the differents environments
const fs = require('fs')
let endPoint
if (process.env.MY_ENV === 'dev') {
endPoint = 'http://my-api-dev/api/v1'
} else if (process.env.MY_ENV === 'test') {
endPoint = 'http://127.0.0.1:7001'
} else {
endPoint = 'http://my-api-pro/api/v1'
}
let template = `
export default {
API_URL: '${endPoint}',
DEVICE_FINGERPRINT: Math.random().toString(36).slice(2)
}
`
fs.writeFile('./src/constants/config.js', template, function (err) {
if (err) {
return console.log(err)
}
console.log('Configuration file has generated')
})
And i have created a custom npm run scripts
to execute react-native run..
My package-json
"scripts": {
"start-ios": "node config-generator.js && react-native run-ios",
"build-ios": "node config-generator.js && react-native run-ios --configuration Release",
"start-android": "node config-generator.js && react-native run-android",
"build-android": "node config-generator.js && cd android/ && ./gradlew assembleRelease",
...
}
Then in my services components simply import the auto generated file:
import config from '../constants/config'
fetch(`${config.API_URL}/login`, params)
use cin.ignore(1000,'\n')
to clear all of chars of the previous cin.get()
in the buffer and it will choose to stop when it meet '\n' or 1000 chars
first.
You could also use float and inline-block to center your nav like the following:
nav li {
float: left;
}
nav {
display: inline-block;
}
One solution that I have employed is to do this:
1) Create a custom management command, e.g.
python manage.py my_cool_command
2) Use cron
(on Linux) or at
(on Windows) to run my command at the required times.
This is a simple solution that doesn't require installing a heavy AMQP stack. However there are nice advantages to using something like Celery, mentioned in the other answers. In particular, with Celery it is nice to not have to spread your application logic out into crontab files. However the cron solution works quite nicely for a small to medium sized application and where you don't want a lot of external dependencies.
EDIT:
In later version of windows the at
command is deprecated for Windows 8, Server 2012 and above. You can use schtasks.exe
for same use.
**** UPDATE **** This the new link of django doc for writing the custom management command
Now you should be able to use the new proxy integration type for Lambda to automatically get the full request in standard shape, rather than configure mappings.
Try just:
powershell.exe -noexit D:\Work\SQLExecutor.ps1 -gettedServerName "MY-PC"
You should watch this: Node Tuts episode 19 - Asynchronous Iteration Patterns
It should answers your questions.
This error message...
selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: crashed
(unknown error: DevToolsActivePort file doesn't exist)
(The process started from chrome location /opt/google/chrome/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)
...implies that the ChromeDriver was unable to initiate/spawn a new WebBrowser i.e. Chrome Browser session.
Your main issue is the Chrome browser is not installed at the default location within your system.
The server i.e. ChromeDriver expects you to have Chrome installed in the default location for each system as per the image below:
1For Linux systems, the ChromeDriver expects /usr/bin/google-chrome
to be a symlink to the actual Chrome binary.
In case you are using a Chrome executable in a non-standard location you have to override the Chrome binary location as follows:
Python Solution:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.binary_location = "C:\\path\\to\\chrome.exe" #chrome binary location specified here
options.add_argument("--start-maximized") #open Browser in maximized mode
options.add_argument("--no-sandbox") #bypass OS security model
options.add_argument("--disable-dev-shm-usage") #overcome limited resource problems
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
driver = webdriver.Chrome(options=options, executable_path=r'C:\path\to\chromedriver.exe')
driver.get('http://google.com/')
Java Solution:
System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe");
ChromeOptions opt = new ChromeOptions();
opt.setBinary("C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"); //chrome binary location specified here
options.addArguments("start-maximized");
options.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation"));
options.setExperimentalOption("useAutomationExtension", false);
WebDriver driver = new ChromeDriver(opt);
driver.get("https://www.google.com/");
The function STR_TO_DATE(COLUMN, '%input_format') can do it, you only have to specify the input format. Example : to convert p052011
SELECT STR_TO_DATE('p052011','p%m%Y') FROM your_table;
The result : 2011-05-00
I had to go through a bit more to force a refresh in VS 2008.
First, there is a Data Sources pane/toolbox (menu trail = Data > Show Data Sources), and a Report Data Sources dialog (menu trail = Report > Data Sources). I had trouble with the Data Sources pane reverting to an earlier property list every time I opened a certain report; it was as if the report designer was overwriting the data definition with the report's cached version thereof.
To remedy this, I had to:
Number 5 forced the report's internal XML copy of the data definition to refresh. Immediately after that, I could build again.
You could also change the repository name you wish to push to in the REPOHOME/.git/config file
(where REPOHOME is the path to your local clone of the repository).
To extrapolate on Felix Kling's comment, you can use .filter()
like this:
var sources = images.map(function (img) {
if(img.src.split('.').pop() === "json") { // if extension is .json
return null; // skip
} else {
return img.src;
}
}).filter(Boolean);
That will remove falsey values from the array that is returned by .map()
You could simplify it further like this:
var sources = images.map(function (img) {
if(img.src.split('.').pop() !== "json") { // if extension is .json
return img.src;
}
}).filter(Boolean);
Or even as a one-liner using an arrow function, object destructuring and the &&
operator:
var sources = images.map(({ src }) => src.split('.').pop() !== "json" && src).filter(Boolean);
import numpy as np
import PIL
def convert_image(image_file):
image = Image.open(image_file) # this could be a 4D array PNG (RGBA)
original_width, original_height = image.size
np_image = np.array(image)
new_image = np.zeros((np_image.shape[0], np_image.shape[1], 3))
# create 3D array
for each_channel in range(3):
new_image[:,:,each_channel] = np_image[:,:,each_channel]
# only copy first 3 channels.
# flushing
np_image = []
return new_image
I have used this URL to obtain multiple currency market quotes.
http://finance.yahoo.com/d/quotes.csv?e=.csv&f=c4l1&s=USD=X,CAD=X,EUR=X
"USD",1.0000
"CAD",1.2458
"EUR",0.8396
They can be parsed in PHP like this:
$symbols = ['USD=X', 'CAD=X', 'EUR=X'];
$url = "http://finance.yahoo.com/d/quotes.csv?e=.csv&f=c4l1&s=".join($symbols, ',');
$quote = array_map( 'str_getcsv', file($url) );
foreach ($quote as $key => $symb) {
$symbol = $quote[$key][0];
$value = $quote[$key][1];
}
fgets would work for you. here is very good documentation on this :-
http://www.cplusplus.com/reference/cstdio/fgets/
If you don't want to use fgets, following method will work for you :-
int readline(FILE *f, char *buffer, size_t len)
{
char c;
int i;
memset(buffer, 0, len);
for (i = 0; i < len; i++)
{
int c = fgetc(f);
if (!feof(f))
{
if (c == '\r')
buffer[i] = 0;
else if (c == '\n')
{
buffer[i] = 0;
return i+1;
}
else
buffer[i] = c;
}
else
{
//fprintf(stderr, "read_line(): recv returned %d\n", c);
return -1;
}
}
return -1;
}
You are triggering the event before the event is even bound.
Just move the triggering
of the event to after attaching the event.
$(document).ready(function() {
$("#checkbox_div input:radio").click(function() {
alert("clicked");
});
$("input:radio:first").prop("checked", true).trigger("click");
});
Using Ramda:
import {addIndex, map} from 'ramda';
const list = [ 'h', 'e', 'l', 'l', 'o'];
const mapIndexed = addIndex(map);
mapIndexed((currElement, index) => {
console.log("The current iteration is: " + index);
console.log("The current element is: " + currElement);
console.log("\n");
return 'X';
}, list);
In order to copy files from HDFS to the local file system the following command could be run:
hadoop dfs -copyToLocal <input> <output>
<input>
: the HDFS directory path (e.g /mydata) that you want to copy<output>
: the destination directory path (e.g. ~/Documents)Put this code wherever you want to insert a new line:
bufferedWriter.newLine();
I got this issue when I used an ajax call to retrieve data from the database. When the controller returned the array it converted it to a boolean. The problem was that I had "invalid characters" like ΓΊ (u with accent).