public class SwapElements {
public static void main(String[] args) {
int[] arr1 = new int[5];
int[] arr2 = {10,20,30,40};
System.out.println("arr1 Before Swapping " + Arrays.toString(arr1));
System.out.println("arr2 Before Swapping " + Arrays.toString(arr2));
int temp[];
arr1[3] = 5;
arr1[0] = 2;
arr1[1] = 3;
arr1[2] = 6;
arr1[4] = 10;
temp = arr1;
arr1 = arr2;
arr2 = temp;
System.out.println("arr1 after Swapping " + Arrays.toString(arr1));
System.out.println("arr2 after Swapping " + Arrays.toString(arr2));
}
}
pip install worked for me, and it failed with a permission issue, which was resolved when I used
sudo pip install pandas
I see that the best sudo workaround is from /tmp: Is it acceptable and safe to run pip install under sudo?
I know there is an accepted answer for this question and many other answers also but I just wanted to add an another case which happened with me was Updating the django and django rest framework to the latest versions to make them work properly without any error.
So all you have to do is just uninstall both django and django rest framework using:
pip uninstall django
pip uninstall djangorestframework
and then install it again using:
pip install django
pip install djangorestframework
You don't need to copy a Python string. They are immutable, and the copy
module always returns the original in such cases, as do str()
, the whole string slice, and concatenating with an empty string.
Moreover, your 'hello'
string is interned (certain strings are). Python deliberately tries to keep just the one copy, as that makes dictionary lookups faster.
One way you could work around this is to actually create a new string, then slice that string back to the original content:
>>> a = 'hello'
>>> b = (a + '.')[:-1]
>>> id(a), id(b)
(4435312528, 4435312432)
But all you are doing now is waste memory. It is not as if you can mutate these string objects in any way, after all.
If all you wanted to know is how much memory a Python object requires, use sys.getsizeof()
; it gives you the memory footprint of any Python object.
For containers this does not include the contents; you'd have to recurse into each container to calculate a total memory size:
>>> import sys
>>> a = 'hello'
>>> sys.getsizeof(a)
42
>>> b = {'foo': 'bar'}
>>> sys.getsizeof(b)
280
>>> sys.getsizeof(b) + sum(sys.getsizeof(k) + sys.getsizeof(v) for k, v in b.items())
360
You can then choose to use id()
tracking to take an actual memory footprint or to estimate a maximum footprint if objects were not cached and reused.
you use that code
ImageView[] ivCard = new ImageView[1];
@override
protected void onCreate(Bundle savedInstanceState)
ivCard[0]=(ImageView)findViewById(R.id.imageView1);
Maybe you wrongly set permission on python3. For instance if for the file permission is set like
`os.chmod('spam.txt', 0777)` --> This will lead to SyntaxError
This syntax was used in Python2. Now if you change like:
os.chmod('spam.txt', 777)
--> This is still worst!! Your permission will be set wrongly since are not on "octal" but on decimal.
Afterwards you will get permission Error if you try for instance to remove the file: PermissionError: [WinError 5] Access is denied:
Solution for python3 is quite easy:
os.chmod('spam.txt', 0o777)
--> The syntax is now ZERO and o "0o"
You can try this:table1.GroupBy(t => t.Text).Select(shape => shape.r)).Distinct();
Implementation wise you will often see inside super() statement in subclasses constructors, something like:
public class A extends AbstractB{
public A(...){
super(String constructorArgForB, ...);
...
}
}
In Swift we can make a function and do as follows
func getCurrentMillis()->Int64{
return Int64(NSDate().timeIntervalSince1970 * 1000)
}
var currentTime = getCurrentMillis()
Though its working fine in Swift 3.0 but we can modify and use the Date
class instead of NSDate
in 3.0
Swift 3.0
func getCurrentMillis()->Int64 {
return Int64(Date().timeIntervalSince1970 * 1000)
}
var currentTime = getCurrentMillis()
I have had the same problem as noted above. I could not get Eclipse to install because of Java incompatibilities. The sequence I followed goes like this:
This took hours of my time. I hope this proves useful.
Thanks to pwc101's comment on this post, this command worked in Kali Linux .
sed -i s/{ctrl+v}{ctrl+m}// {filename}
Make sure you replace the bits in brackets, {}
. I.e. {ctrl+m}
means press Ctrl key and the M key together.
Better if SQL will be optimized with addion of LIMIT 1
in the end:
$query = "select id from games LIMIT 1";
SO ANSWER IS (works on php 5.6.3):
If you want to get first item of first row(even if it is not ID column):
queryExec($query) -> fetch_array()[0];
If you want to get first row(single item from DB)
queryExec($query) -> fetch_assoc();
If you want to some exact column from first row
queryExec($query) -> fetch_assoc()['columnName'];
or need to fix query and use first written way :)
Nav.js comp inside components folder
export {Nav}
index.js in component folder
export {Nav} from './Nav';
export {Another} from './Another';
import anywhere
import {Nav, Another} from './components'
The output looks correct to me:
Invalid JavaScript code: sun.org.mozilla.javascript.internal.EvaluatorException: missing } after property list (<Unknown source>) in <Unknown source>; at line number 1
I think Invalid Javascript code: ..
is the start of the exception message.
Normally the stacktrace isn't returned with the message:
try {
throw new RuntimeException("hu?\ntrace-line1\ntrace-line2");
} catch (Exception e) {
System.out.println(e.getMessage()); // prints "hu?"
}
So maybe the code you are calling catches an exception and rethrows a ScriptException
. In this case maybe e.getCause().getMessage()
can help you.
A better alternative is provided in ES6 using Sets. So, instead of declaring Arrays, it is recommended to use Sets if you need to have an array that shouldn't add duplicates.
var array = new Set();
array.add(1);
array.add(2);
array.add(3);
console.log(array);
// Prints: Set(3) {1, 2, 3}
array.add(2); // does not add any new element
console.log(array);
// Still Prints: Set(3) {1, 2, 3}
Adapting paxdiablo's solution, I run on the 28th and 29th of February. The data from the 29th overwrites the 28th.
# min hr date month dow
55 23 31 1,3,5,7,8,10,12 * /path/monthly_copy_data.sh
55 23 30 4,6,9,11 * /path/monthly_copy_data.sh
55 23 28,29 2 * /path/monthly_copy_data.sh
If you are using TFS
Remove the NuGet.exe
and NuGet.targets
files from the solution's .nuget
folder. Make sure the files themselves are also removed from the solution workspace.
Retain the NuGet.Config
file to continue to bypass adding packages to source control.
Edit each project file (e.g., .csproj, .vbproj) in the solution and remove any references to the NuGet.targets
file. Open the project file(s) in the editor of your choice and remove the following settings:
<RestorePackages>true</RestorePackages>
...
<Import Project="$(SolutionDir)\.nuget\nuget.targets" />
...
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" />
</Target>
If you are not using TFS
Remove the .nuget
folder from your solution. Make sure the folder itself is also removed from the solution workspace.
Edit each project file (e.g., .csproj, .vbproj) in the solution and remove any references to the NuGet.targets
file. Open the project file(s) in the editor of your choice and remove the following settings:
<RestorePackages>true</RestorePackages>
...
<Import Project="$(SolutionDir)\.nuget\nuget.targets" />
...
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" />
</Target>
Reference: Migrating MSBuild-Integrated solutions to use Automatic Package Restore
If you are trying to use mysqlclient
on WINDOWS with this failure, try to install the lower version instead:
pip install mysqlclient==1.3.4
Convert.ToInt32(myobject);
This will handle the case where myobject is null and return 0, instead of throwing an exception.
This can be done without regex
which is more efficient:
var questionText = "1 ding ?"
var index = 0;
var num = "";
do
{
num += questionText[index];
} while (questionText[++index] >= "0" && questionText[index] <= "9");
questionText = questionText.substring(num.length);
And as a bonus, it also stores the number, which may be useful to some people.
LPCWSTR
is equivalent to wchar_t const *
. It's a pointer to a wide character string that won't be modified by the function call.
You can assign to LPCWSTR
s by prepending a L to a string literal: LPCWSTR *myStr = L"Hello World";
LPCTSTR and any other T types, take a string type depending on the Unicode settings for your project. If _UNICODE
is defined for your project, the use of T types is the same as the wide character forms, otherwise the Ansi forms. The appropriate function will also be called this way: FindWindowEx
is defined as FindWindowExA
or FindWindowExW
depending on this definition.
What worked for me:
Preferences-General-Default working directory-Browse Switch from global to local mirror
Working on a Mac. 10.10.3
The code below would be a bit more efficient than the answers presented above when dealing with larger datasets.
SELECT * FROM Call WHERE
NOT EXISTS (SELECT 'x' FROM Phone_book where
Phone_book.phone_number = Call.phone_number)
If you look at the output you receive from print()
and also in your Traceback, you'll see the value you get back is not a string, it's a bytes object (prefixed by b
):
b'{\n "note":"This file .....
If you fetch the URL using a tool such as curl -v
, you will see that the content type is
Content-Type: application/json; charset=utf-8
So it's JSON, encoded as UTF-8, and Python is considering it a byte stream, not a simple string. In order to parse this, you need to convert it into a string first.
Change the last line of code to this:
info = json.loads(js.decode("utf-8"))
This only covers a simple case:
a = ‘Quattro TT’
print tuple(a)
If you use only delimiter like ‘,’, then it could work.
I used a string from configparser
like so:
list_users = (‘test1’, ‘test2’, ‘test3’)
and the i get from file
tmp = config_ob.get(section_name, option_name)
>>>”(‘test1’, ‘test2’, ‘test3’)”
In this case the above solution does not work. However, this does work:
def fot_tuple(self, some_str):
# (‘test1’, ‘test2’, ‘test3’)
some_str = some_str.replace(‘(‘, ”)
# ‘test1’, ‘test2’, ‘test3’)
some_str = some_str.replace(‘)’, ”)
# ‘test1’, ‘test2’, ‘test3’
some_str = some_str.replace(“‘, ‘”, ‘,’)
# ‘test1,test2,test3’
some_str = some_str.replace(“‘”, ‘,’)
# test1,test2,test3
# and now i could convert to tuple
return tuple(item for item in some_str.split(‘,’) if item.strip())
You can find details about these in this Android - Command Line Tools
tl;dr:
SDK Tools:
Build Tools:
Platform Tools:
To read characters try
scan("/PathTo/file.csv", "")
If you're reading numeric values, then just use
scan("/PathTo/file.csv")
scan
by default will use white space as separator. The type of the second arg defines 'what' to read (defaults to double()).
SOAP (communication protocol) for communication between applications. Uses HTTP (port 80) or SMTP ( port 25 or 2525 ), for message negotiation and transmission.
Ladislav's answer updated to use DbContext (introduced in EF 4.1):
public void ChangePassword(int userId, string password)
{
var user = new User() { Id = userId, Password = password };
using (var db = new MyEfContextName())
{
db.Users.Attach(user);
db.Entry(user).Property(x => x.Password).IsModified = true;
db.SaveChanges();
}
}
Remove -Werror
from your Make or CMake files, as suggested in this post
You say in a comment you want to get "15.09.2016".
For this, use Date
and DateFormatter
:
let date = Date()
let formatter = DateFormatter()
Give the format you want to the formatter:
formatter.dateFormat = "dd.MM.yyyy"
Get the result string:
let result = formatter.string(from: date)
Set your label:
label.text = result
Result:
15.09.2016
The reason why your current approach doesn't work is because Jackson is used by default to serialize and to deserialize objects. However, it doesn't know how to serialize the JSONObject
. If you want to create a dynamic JSON structure, you can use a Map
, for example:
@GetMapping
public Map<String, String> sayHello() {
HashMap<String, String> map = new HashMap<>();
map.put("key", "value");
map.put("foo", "bar");
map.put("aa", "bb");
return map;
}
This will lead to the following JSON response:
{ "key": "value", "foo": "bar", "aa": "bb" }
This is a bit limited, since it may become a bit more difficult to add child objects. Jackson has its own mechanism though, using ObjectNode
and ArrayNode
. To use it, you have to autowire ObjectMapper
in your service/controller. Then you can use:
@GetMapping
public ObjectNode sayHello() {
ObjectNode objectNode = mapper.createObjectNode();
objectNode.put("key", "value");
objectNode.put("foo", "bar");
objectNode.put("number", 42);
return objectNode;
}
This approach allows you to add child objects, arrays, and use all various types.
I got the same error, but it was resolved if you add the libraries of selenium (again if you haven't), if you are using INTELIJ
project>projectStructure>Module>+>add the selenium jars (both from lib folder and outside ones.).
Same needs to be done for other IDE's as well, like eclipse.
Swift is statically typed so the performSelector:
methods are to fall by the wayside.
Instead, use GCD to dispatch a suitable block to the relevant queue — in this case it'll presumably be the main queue since it looks like you're doing UIKit work.
EDIT: the relevant performSelector:
is also notably missing from the Swift version of the NSRunLoop
documentation ("1 Objective-C symbol hidden") so you can't jump straight in with that. With that and its absence from the Swiftified NSObject
I'd argue it's pretty clear what Apple is thinking here.
Slight modification to the accepted answer.
def resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
if hasattr(sys, '_MEIPASS'):
return os.path.join(sys._MEIPASS, relative_path)
return os.path.join(os.path.abspath("."), relative_path)
Any simple constraint should do the job, if an exception is acceptable. Examples :
Sorry is this seems deceptively simple. I know it looks bad confronted to the link you share with us. ;-(
But I neverleless give this answer, because it seem to fill your need. (If not, it may trigger your updating your requirements, which would be "a Good Thing"(TM) also).
Edited: If an insert would break the database unique constraint, an exception is throw at the database level, relayed by the driver. It will certainly stop your script, with a failure. It must be possible in PHP to adress that case ...
To keep this question current it is worth highlighting that AssemblyInformationalVersion
is used by NuGet and reflects the package version including any pre-release suffix.
For example an AssemblyVersion of 1.0.3.* packaged with the asp.net core dotnet-cli
dotnet pack --version-suffix ci-7 src/MyProject
Produces a package with version 1.0.3-ci-7 which you can inspect with reflection using:
CustomAttributeExtensions.GetCustomAttribute<AssemblyInformationalVersionAttribute>(asm);
write it like this
p {
padding-bottom: 3cm;
}
or
p {
margin-bottom: 3cm;
}
In my case, this error occur when i tried to use gridView
I resolved it by removing this line from build.grade(Module) file
implementation 'com.android.support:gridlayout-v7:28.0.0-alpha3'
In the case of nesting the LinkButton within a Repeater you must using something similar to the following:
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="MyUpdate">LinkButton</asp:LinkButton>
protected void Repeater1_OnItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName.Equals("MyUpdate"))
{
// some code
}
}
I was able to get it working with code only, i.e. no need to use keytool:
import com.netflix.config.DynamicBooleanProperty;
import com.netflix.config.DynamicIntProperty;
import com.netflix.config.DynamicPropertyFactory;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager;
import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
import org.apache.http.impl.nio.reactor.IOReactorConfig;
import org.apache.http.nio.conn.NoopIOSessionStrategy;
import org.apache.http.nio.conn.SchemeIOSessionStrategy;
import org.apache.http.nio.conn.ssl.SSLIOSessionStrategy;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
public class Test
{
private static final DynamicIntProperty MAX_TOTAL_CONNECTIONS = DynamicPropertyFactory.getInstance().getIntProperty("X.total.connections", 40);
private static final DynamicIntProperty ROUTE_CONNECTIONS = DynamicPropertyFactory.getInstance().getIntProperty("X.total.connections", 40);
private static final DynamicIntProperty CONNECT_TIMEOUT = DynamicPropertyFactory.getInstance().getIntProperty("X.connect.timeout", 60000);
private static final DynamicIntProperty SOCKET_TIMEOUT = DynamicPropertyFactory.getInstance().getIntProperty("X.socket.timeout", -1);
private static final DynamicIntProperty CONNECTION_REQUEST_TIMEOUT = DynamicPropertyFactory.getInstance().getIntProperty("X.connectionrequest.timeout", 60000);
private static final DynamicBooleanProperty STALE_CONNECTION_CHECK = DynamicPropertyFactory.getInstance().getBooleanProperty("X.checkconnection", true);
public static void main(String[] args) throws Exception
{
SSLContext sslcontext = SSLContexts.custom()
.useTLS()
.loadTrustMaterial(null, new TrustStrategy()
{
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException
{
return true;
}
})
.build();
SSLIOSessionStrategy sslSessionStrategy = new SSLIOSessionStrategy(sslcontext, new AllowAll());
Registry<SchemeIOSessionStrategy> sessionStrategyRegistry = RegistryBuilder.<SchemeIOSessionStrategy>create()
.register("http", NoopIOSessionStrategy.INSTANCE)
.register("https", sslSessionStrategy)
.build();
DefaultConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(IOReactorConfig.DEFAULT);
PoolingNHttpClientConnectionManager connectionManager = new PoolingNHttpClientConnectionManager(ioReactor, sessionStrategyRegistry);
connectionManager.setMaxTotal(MAX_TOTAL_CONNECTIONS.get());
connectionManager.setDefaultMaxPerRoute(ROUTE_CONNECTIONS.get());
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(SOCKET_TIMEOUT.get())
.setConnectTimeout(CONNECT_TIMEOUT.get())
.setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT.get())
.setStaleConnectionCheckEnabled(STALE_CONNECTION_CHECK.get())
.build();
CloseableHttpAsyncClient httpClient = HttpAsyncClients.custom()
.setSSLStrategy(sslSessionStrategy)
.setConnectionManager(connectionManager)
.setDefaultRequestConfig(requestConfig)
.build();
httpClient.start();
// use httpClient...
}
private static class AllowAll implements X509HostnameVerifier
{
@Override
public void verify(String s, SSLSocket sslSocket) throws IOException
{}
@Override
public void verify(String s, X509Certificate x509Certificate) throws SSLException {}
@Override
public void verify(String s, String[] strings, String[] strings2) throws SSLException
{}
@Override
public boolean verify(String s, SSLSession sslSession)
{
return true;
}
}
}
You can use the focusout event to detect keyboard dismissal. It's like blur, but bubbles. It will fire when the keyboard closes (but also in other cases, of course). In Safari and Chrome the event can only be registered with addEventListener, not with legacy methods. Here is an example I used to restore a Phonegap app after keyboard dismissal.
document.addEventListener('focusout', function(e) {window.scrollTo(0, 0)});
Without this snippet, the app container stayed in the up-scrolled position until page refresh.
Not so hard:
#include <thread>
void Test::runMultiThread()
{
std::thread t1(&Test::calculate, this, 0, 10);
std::thread t2(&Test::calculate, this, 11, 20);
t1.join();
t2.join();
}
If the result of the computation is still needed, use a future instead:
#include <future>
void Test::runMultiThread()
{
auto f1 = std::async(&Test::calculate, this, 0, 10);
auto f2 = std::async(&Test::calculate, this, 11, 20);
auto res1 = f1.get();
auto res2 = f2.get();
}
If you're doing it via CMD as you say, then you can just enter the command like so:
path\to\your.exe
which will open it within the same window. For example in C++:
system("path\\to\\your.exe"); // Double backslash for escaping
will open your.exe
in the current CMD window. Likewise to start with a new window, just go for:
system("start path\\to\\your.exe");
If you go for the first option, you would have to clear your screen unless you wanted to have the command to open your.exe
on the screen still.
There is a std::swap
in <algorithm>
Short answer, no, there is no native support for private properties with ES6 classes.
But you could mimic that behaviour by not attaching the new properties to the object, but keeping them inside a class constructor, and use getters and setters to reach the hidden properties. Note that the getters and setters gets redefine on each new instance of the class.
ES6
class Person {
constructor(name) {
var _name = name
this.setName = function(name) { _name = name; }
this.getName = function() { return _name; }
}
}
ES5
function Person(name) {
var _name = name
this.setName = function(name) { _name = name; }
this.getName = function() { return _name; }
}
Here is simple code. Hope it is working
$(document).ready(function() {_x000D_
var text_max = 99;_x000D_
$('#textarea_feedback').html(text_max + ' characters remaining');_x000D_
_x000D_
$('#textarea').keyup(function() {_x000D_
var text_length = $('#textarea').val().length;_x000D_
var text_remaining = text_max - text_length;_x000D_
_x000D_
$('#textarea_feedback').html(text_remaining + ' characters remaining');_x000D_
});_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<textarea id="textarea" rows="8" cols="30" maxlength="99" ></textarea>_x000D_
<div id="textarea_feedback"></div>
_x000D_
If javascript is accepted as an answer, I made a jQuery plugin to address this issue (for more information about the issue see CSS: Truncate table cells, but fit as much as possible).
To use the plugin just type
$('selector').tableoverflow();
Plugin: https://github.com/marcogrcr/jquery-tableoverflow
Full example: http://jsfiddle.net/Cw7TD/3/embedded/result/
I had a similar issue, but it was related to Hibernate's bi-directional relationships. I wanted to show one side of the relationship and programmatically ignore the other, depending on what view I was dealing with. If you can't do that, you end up with nasty StackOverflowException
s. For instance, if I had these objects
public class A{
Long id;
String name;
List<B> children;
}
public class B{
Long id;
A parent;
}
I would want to programmatically ignore the parent
field in B if I were looking at A, and ignore the children
field in A if I were looking at B.
I started off using mixins to do this, but that very quickly becomes horrible; you have so many useless classes laying around that exist solely to format data. I ended up writing my own serializer to handle this in a cleaner way: https://github.com/monitorjbl/json-view.
It allows you programmatically specify what fields to ignore:
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(JsonView.class, new JsonViewSerializer());
mapper.registerModule(module);
List<A> list = getListOfA();
String json = mapper.writeValueAsString(JsonView.with(list)
.onClass(B.class, match()
.exclude("parent")));
It also lets you easily specify very simplified views through wildcard matchers:
String json = mapper.writeValueAsString(JsonView.with(list)
.onClass(A.class, match()
.exclude("*")
.include("id", "name")));
In my original case, the need for simple views like this was to show the bare minimum about the parent/child, but it also became useful for our role-based security. Less privileged views of objects needed to return less information about the object.
All of this comes from the serializer, but I was using Spring MVC in my app. To get it to properly handle these cases, I wrote an integration that you can drop in to existing Spring controller classes:
@Controller
public class JsonController {
private JsonResult json = JsonResult.instance();
@Autowired
private TestObjectService service;
@RequestMapping(method = RequestMethod.GET, value = "/bean")
@ResponseBody
public List<TestObject> getTestObject() {
List<TestObject> list = service.list();
return json.use(JsonView.with(list)
.onClass(TestObject.class, Match.match()
.exclude("int1")
.include("ignoredDirect")))
.returnValue();
}
}
Both are available on Maven Central. I hope it helps someone else out there, this is a particularly ugly problem with Jackson that didn't have a good solution for my case.
When you want to have cross component interaction, then you need to know what are @Input , @Output , EventEmitter and Subjects.
If the relation between components is parent- child or vice versa we use @input & @output with event emitter..
@output emits an event and you need to emit using event emitter.
If it's not parent child relationship.. then you have to use subjects or through a common service.
You can make an Ajax Call (Note: This solution requires JQuery):
example.php
<?php
setcookie('CookieEnabledTest', 'check', time()+3600);
?>
<script type="text/javascript">
CookieCheck();
function CookieCheck()
{
$.post
(
'ajax.php',
{
cmd: 'cookieCheck'
},
function (returned_data, status)
{
if (status === "success")
{
if (returned_data === "enabled")
{
alert ("Cookies are activated.");
}
else
{
alert ("Cookies are not activated.");
}
}
}
);
}
</script>
ajax.php
$cmd = filter_input(INPUT_POST, "cmd");
if ( isset( $cmd ) && $cmd == "cookieCheck" )
{
echo (isset($_COOKIE['CookieEnabledTest']) && $_COOKIE['CookieEnabledTest']=='check') ? 'enabled' : 'disabled';
}
As result an alert box appears which shows wheter cookies are enabled or not. Of course you don't have to show an alert box, from here you can take other steps to deal with deactivated cookies.
If you put together the answers so far, clean up and improve, you would arrive at this superior query:
UPDATE sales
SET status = 'ACTIVE'
WHERE (saleprice, saledate) IN (
SELECT saleprice, saledate
FROM sales
GROUP BY saleprice, saledate
HAVING count(*) = 1
);
Which is much faster than either of them. Nukes the performance of the currently accepted answer by factor 10 - 15 (in my tests on PostgreSQL 8.4 and 9.1).
But this is still far from optimal. Use a NOT EXISTS
(anti-)semi-join for even better performance. EXISTS
is standard SQL, has been around forever (at least since PostgreSQL 7.2, long before this question was asked) and fits the presented requirements perfectly:
UPDATE sales s
SET status = 'ACTIVE'
WHERE NOT EXISTS (
SELECT FROM sales s1 -- SELECT list can be empty for EXISTS
WHERE s.saleprice = s1.saleprice
AND s.saledate = s1.saledate
AND s.id <> s1.id -- except for row itself
)
AND s.status IS DISTINCT FROM 'ACTIVE'; -- avoid empty updates. see below
db<>fiddle here
Old SQL Fiddle
If you don't have a primary or unique key for the table (id
in the example), you can substitute with the system column ctid
for the purpose of this query (but not for some other purposes):
AND s1.ctid <> s.ctid
Every table should have a primary key. Add one if you didn't have one, yet. I suggest a serial
or an IDENTITY
column in Postgres 10+.
Related:
The subquery in the EXISTS
anti-semi-join can stop evaluating as soon as the first dupe is found (no point in looking further). For a base table with few duplicates this is only mildly more efficient. With lots of duplicates this becomes way more efficient.
For rows that already have status = 'ACTIVE'
this update would not change anything, but still insert a new row version at full cost (minor exceptions apply). Normally, you do not want this. Add another WHERE
condition like demonstrated above to avoid this and make it even faster:
If status
is defined NOT NULL
, you can simplify to:
AND status <> 'ACTIVE';
The data type of the column must support the <>
operator. Some types like json
don't. See:
This query (unlike the currently accepted answer by Joel) does not treat NULL values as equal. The following two rows for (saleprice, saledate)
would qualify as "distinct" (though looking identical to the human eye):
(123, NULL)
(123, NULL)
Also passes in a unique index and almost anywhere else, since NULL values do not compare equal according to the SQL standard. See:
OTOH, GROUP BY
, DISTINCT
or DISTINCT ON ()
treat NULL values as equal. Use an appropriate query style depending on what you want to achieve. You can still use this faster query with IS NOT DISTINCT FROM
instead of =
for any or all comparisons to make NULL compare equal. More:
If all columns being compared are defined NOT NULL
, there is no room for disagreement.
Other possible solution:
tv.setText(Integer.toString(a1)); // where a1 - int value
Assuming you want an icon on the right (or left) then this should work best:
.show-hide-button::after {
content:"";
background-repeat: no-repeat;
background-size: contain;
display: inline-block;
background-size: 1em;
width: 1em;
height: 1em;
background-position: 0 2px;
margin-left: .5em;
}
.show-hide-button.shown::after {
background-image: url(img/eye.svg);
}
You could also do background-size: contain;
, but that should be mostly the same. the background-position
will depened on your image.
Then you can easily do an alternative state on hover:
.show-hide-button.shown:hover::after {
background-image: url(img/eye-no.svg);
}
There is an in-built stopword list in NLTK
made up of 2,400 stopwords for 11 languages (Porter et al), see http://nltk.org/book/ch02.html
>>> from nltk import word_tokenize
>>> from nltk.corpus import stopwords
>>> stop = set(stopwords.words('english'))
>>> sentence = "this is a foo bar sentence"
>>> print([i for i in sentence.lower().split() if i not in stop])
['foo', 'bar', 'sentence']
>>> [i for i in word_tokenize(sentence.lower()) if i not in stop]
['foo', 'bar', 'sentence']
I recommend looking at using tf-idf to remove stopwords, see Effects of Stemming on the term frequency?
You are getting the WebView before setting the Content view so the wv is probably null.
public class ViewWeb extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
WebView wv;
wv = (WebView) findViewById(R.id.webView1);
wv.loadUrl("file:///android_asset/aboutcertified.html"); // now it will not fail here
}
}
I use the below query for tracing application activity on a SQL server that does not have trace profiler enabled. The method uses Query Store (SQL Server 2016+) instead of the DMV's. This gives better ability to look into historical data, as well as faster lookups. It is very efficient to capture short-running queries that can't be captured by sp_who/sp_whoisactive.
/* Adjust script to your needs.
Run full script (F5) -> Interact with UI -> Run full script again (F5)
Output will contain the queries completed in that timeframe.
*/
/* Requires Query Store to be enabled:
ALTER DATABASE <db> SET QUERY_STORE = ON
ALTER DATABASE <db> SET QUERY_STORE (OPERATION_MODE = READ_WRITE, MAX_STORAGE_SIZE_MB = 100000)
*/
USE <db> /* Select your DB */
IF OBJECT_ID('tempdb..#lastendtime') IS NULL
SELECT GETUTCDATE() AS dt INTO #lastendtime
ELSE IF NOT EXISTS (SELECT * FROM #lastendtime)
INSERT INTO #lastendtime VALUES (GETUTCDATE())
;WITH T AS (
SELECT
DB_NAME() AS DBName
, s.name + '.' + o.name AS ObjectName
, qt.query_sql_text
, rs.runtime_stats_id
, p.query_id
, p.plan_id
, CAST(p.last_execution_time AS DATETIME) AS last_execution_time
, CASE WHEN p.last_execution_time > #lastendtime.dt THEN 'X' ELSE '' END AS New
, CAST(rs.last_duration / 1.0e6 AS DECIMAL(9,3)) last_duration_s
, rs.count_executions
, rs.last_rowcount
, rs.last_logical_io_reads
, rs.last_physical_io_reads
, q.query_parameterization_type_desc
FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY plan_id, runtime_stats_id ORDER BY runtime_stats_id DESC) AS recent_stats_in_current_priod
FROM sys.query_store_runtime_stats
) AS rs
INNER JOIN sys.query_store_runtime_stats_interval AS rsi ON rsi.runtime_stats_interval_id = rs.runtime_stats_interval_id
INNER JOIN sys.query_store_plan AS p ON p.plan_id = rs.plan_id
INNER JOIN sys.query_store_query AS q ON q.query_id = p.query_id
INNER JOIN sys.query_store_query_text AS qt ON qt.query_text_id = q.query_text_id
LEFT OUTER JOIN sys.objects AS o ON o.object_id = q.object_id
LEFT OUTER JOIN sys.schemas AS s ON s.schema_id = o.schema_id
CROSS APPLY #lastendtime
WHERE rsi.start_time <= GETUTCDATE() AND GETUTCDATE() < rsi.end_time
AND recent_stats_in_current_priod = 1
/* Adjust your filters: */
-- AND (s.name IN ('<myschema>') OR s.name IS NULL)
UNION
SELECT NULL,NULL,NULL,NULL,NULL,NULL,dt,NULL,NULL,NULL,NULL,NULL,NULL, NULL
FROM #lastendtime
)
SELECT * FROM T
WHERE T.query_sql_text IS NULL OR T.query_sql_text NOT LIKE '%#lastendtime%' -- do not show myself
ORDER BY last_execution_time DESC
TRUNCATE TABLE #lastendtime
INSERT INTO #lastendtime VALUES (GETUTCDATE())
For example css files are in folder named CSS
and html files are in folder HTML
, and both these are in folder named XYZ
means we refer css files in html as
<link rel="stylesheet" type="text/css" href="./../CSS/style.css" />
Here ..
moves up to HTML
and .
refers to the current directory XYZ
---by this logic you would just reference as:
<link rel="stylesheet" type="text/css" href="CSS/style.css" />
One liner, but be careful if you have a multi-user repository - this will change all commits to have the same (new) author and committer.
git filter-branch -f --env-filter "GIT_AUTHOR_NAME='Newname'; GIT_AUTHOR_EMAIL='new@email'; GIT_COMMITTER_NAME='Newname'; GIT_COMMITTER_EMAIL='new@email';" HEAD
With linebreaks in the string (which is possible in bash):
git filter-branch -f --env-filter "
GIT_AUTHOR_NAME='Newname'
GIT_AUTHOR_EMAIL='new@email'
GIT_COMMITTER_NAME='Newname'
GIT_COMMITTER_EMAIL='new@email'
" HEAD
Probably easiest way is to PInvoke LogonUser Win32 API.e.g.
MSDN Reference here...
Definitely want to use logon type
LOGON32_LOGON_NETWORK (3)
This creates a lightweight token only - perfect for AuthN checks. (other types can be used to build interactive sessions etc.)
Assuming that the question is asking what's the minimum bits required for you to store
My approach to this question would be:
This problem can be solved this way by dividing 999 by 2 recursively. However, it's simpler to use the power of maths to help us. Essentially, we're solving n for the equation below:
2^n = 999
nlog2 = log999
n ~ 10
You'll need 10 bits to store 3 digit number.
Use similar approach to solve the other subquestions!
Hope this helps!
I know it's a "very long time" since this question was first asked. Just in case, if it helps someone,
Adding relationships is well supported by MS via SQL Server Compact Tool Box (https://sqlcetoolbox.codeplex.com/). Just install it, then you would get the option to connect to the Compact Database using the Server Explorer Window. Right click on the primary table , select "Table Properties". You should have the following window, which contains "Add Relations" tab allowing you to add relations.
The simplest and also the most compact solution (for v2.3.3):
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.writeValueAsString(obj)
In fact when you open the pom.xml, you should see 5 tabs in the bottom. Click the pom.xml, and you can type whatever dependencies you want.
Is there are more correct way?
Yes, there is.
LocalDate.now(
ZoneId.of( "America/Montreal" )
).atStartOfDay(
ZoneId.of( "America/Montreal" )
)
Java 8 and later now has the new java.time framework built-in. See Tutorial. Inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project.
Some examples follow, using java.time. Note how they specify a time zone. If omitted, your JVM’s current default time zone. That default can vary, even changing at any moment during runtime, so I suggest you specify a time zone explicitly rather than rely implicitly on the default.
Here is an example of date-only, without time-of-day nor time zone.
ZoneId zonedId = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( zonedId );
System.out.println( "today : " + today );
today : 2015-10-19
Here is an example of getting current date-time.
ZoneId zonedId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.now( zonedId );
System.out.println( "zdt : " + zdt );
When run:
zdt : 2015-10-19T18:07:02.910-04:00[America/Montreal]
The Question asks for the date-time where the time is set to zero. This assumes the first moment of the day is always the time 00:00:00.0
but that is not always the case. Daylight Saving Time (DST) and perhaps other anomalies mean the day may begin at a different time such as 01:00.0
.
Fortunately, java.time has a facility to determine the first moment of a day appropriate to a particular time zone, LocalDate::atStartOfDay
. Let's see some code using the LocalDate
named today
and the ZoneId
named zoneId
from code above.
ZonedDateTime todayStart = today.atStartOfDay( zoneId );
zdt : 2015-10-19T00:00:00-04:00[America/Montreal]
If you must have a java.util.Date for use with classes not yet updated to work with the java.time types, convert. Call the java.util.Date.from( Instant instant )
method.
java.util.Date date = java.util.Date.from( zdt.toInstant() );
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Echoing f.in and f.out will seperate the concept of what to loop and what not to loop when used in a for /f loop.
::Get the files seperated
echo f.in>files_to_pass_through.txt
echo f.out>>files_to_pass_through.txt
for /F %%a in (files_to_pass_through.txt) do (
for /R %%b in (*.*) do (
if "%%a" NEQ "%%b" (
echo %%b>>dont_pass_through_these.txt
)
)
)
::I'm assuming the base name is the whole string "f".
::If I'm right then all the files begin with "f".
::So all you have to do is display "f". right?
::But that would be too easy.
::Let's do this the right way.
for /f %%C in (dont_pass_through_these.txt)
::displays the filename and not the extention
echo %~nC
)
Although you didn't ask, a good way to pass commands into f.in and f.out would be to...
for /F %%D "tokens=*" in (dont_pass_through_these.txt) do (
for /F %%E in (%%D) do (
start /wait %%E
)
)
A link to all the Windows XP commands:link
I apologize if I did not answer this correctly. The question was very hard for me to read.
The best option now is to install the Microsoft Visual Studio add on called Productivity Power Tools.
With this comes "Solution Navigator" (alternative to Solution Explorer, with a lot of benefits) - which then you can use to filter the files to only show "Open". You can even filter files to show "Edited" and "Unsaved".
I tried Atom and it looks really nice BUT there is one major problem (at least in v 0.84):
It doesn't support vertical select Alt+Drag - this is a must for every modern code editor.
You need to use a single object of that list whoose data you are inflating on ListView
. If reference is change then notifyDataSetChanged()
does't work .Whenever You are deleting elements from list view also delete them from the list you are using whether it is a ArrayList<> or Something else then Call
notifyDataSetChanged()
on object of Your adapter class.
So here see how i managed it in my adapter see below
public class CountryCodeListAdapter extends BaseAdapter implements OnItemClickListener{
private Context context;
private ArrayList<CountryDataObject> dObj;
private ViewHolder holder;
private Typeface itemFont;
private int selectedPosition=-1;
private ArrayList<CountryDataObject> completeList;
public CountryCodeListAdapter(Context context, ArrayList<CountryDataObject> dObj) {
this.context = context;
this.dObj=dObj;
completeList=new ArrayList<CountryDataObject>();
completeList.addAll(dObj);
itemFont=Typeface.createFromAsset(context.getAssets(), "CaviarDreams.ttf");
}
@Override
public int getCount() {
return dObj.size();
}
@Override
public Object getItem(int position) {
return dObj.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View view, ViewGroup parent) {
if(view==null){
holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.states_inflator_layout, null);
holder.textView = ((TextView)view.findViewById(R.id.stateNameInflator));
holder.checkImg=(ImageView)view.findViewById(R.id.checkBoxState);
view.setTag(holder);
}else{
holder = (ViewHolder) view.getTag();
}
holder.textView.setText(dObj.get(position).getCountryName());
holder.textView.setTypeface(itemFont);
if(position==selectedPosition)
{
holder.checkImg.setImageResource(R.drawable.check);
}
else
{
holder.checkImg.setImageResource(R.drawable.uncheck);
}
return view;
}
private class ViewHolder{
private TextView textView;
private ImageView checkImg;
}
public void getFilter(String name) {
dObj.clear();
if(!name.equals("")){
for (CountryDataObject item : completeList) {
if(item.getCountryName().toLowerCase().startsWith(name.toLowerCase(),0)){
dObj.add(item);
}
}
}
else {
dObj.addAll(completeList);
}
selectedPosition=-1;
notifyDataSetChanged();
notifyDataSetInvalidated();
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Registration reg=(Registration)context;
selectedPosition=position;
reg.setSelectedCountryCode("+"+dObj.get(position).getCountryCode());
notifyDataSetChanged();
}
}
Select constraint_name,constraint_type from user_constraints where table_name** **= ‘TABLE_NAME’ ;
(This will list the primary key and then)
Select column_name,position from user_cons_cloumns where constraint_name=’PK_XYZ’;
(This will give you the column, here PK_XYZ is the primay key name)
Maybe declaring a range might workout better for you.
// fill in the starting and ending range programmatically this is just an example.
string startRange = "A1";
string endRange = "A1";
Excel.Range currentRange = (Excel.Range)excelWorksheet.get_Range(startRange , endRange );
currentRange.Style.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;
F# is not yet-another-programming-language if you are comparing it to C#, C++, VB. C#, C, VB are all imperative or procedural programming languages. F# is a functional programming language.
Two main benefits of functional programming languages (compared to imperative languages) are 1. that they don't have side-effects. This makes mathematical reasoning about properties of your program a lot easier. 2. that functions are first class citizens. You can pass functions as parameters to another functions just as easily as you can other values.
Both imperative and functional programming languages have their uses. Although I have not done any serious work in F# yet, we are currently implementing a scheduling component in one of our products based on C# and are going to do an experiment by coding the same scheduler in F# as well to see if the correctness of the implementation can be validated more easily than with the C# equivalent.
So this only really works if your having issues saving to a jdbc driver like sqlserver, but it's really helpful for errors you will run into with syntax and types.
import org.apache.spark.sql.jdbc.{JdbcDialects, JdbcType, JdbcDialect}
import org.apache.spark.sql.jdbc.JdbcType
val SQLServerDialect = new JdbcDialect {
override def canHandle(url: String): Boolean = url.startsWith("jdbc:jtds:sqlserver") || url.contains("sqlserver")
override def getJDBCType(dt: DataType): Option[JdbcType] = dt match {
case StringType => Some(JdbcType("VARCHAR(5000)", java.sql.Types.VARCHAR))
case BooleanType => Some(JdbcType("BIT(1)", java.sql.Types.BIT))
case IntegerType => Some(JdbcType("INTEGER", java.sql.Types.INTEGER))
case LongType => Some(JdbcType("BIGINT", java.sql.Types.BIGINT))
case DoubleType => Some(JdbcType("DOUBLE PRECISION", java.sql.Types.DOUBLE))
case FloatType => Some(JdbcType("REAL", java.sql.Types.REAL))
case ShortType => Some(JdbcType("INTEGER", java.sql.Types.INTEGER))
case ByteType => Some(JdbcType("INTEGER", java.sql.Types.INTEGER))
case BinaryType => Some(JdbcType("BINARY", java.sql.Types.BINARY))
case TimestampType => Some(JdbcType("DATE", java.sql.Types.DATE))
case DateType => Some(JdbcType("DATE", java.sql.Types.DATE))
// case DecimalType.Fixed(precision, scale) => Some(JdbcType("NUMBER(" + precision + "," + scale + ")", java.sql.Types.NUMERIC))
case t: DecimalType => Some(JdbcType(s"DECIMAL(${t.precision},${t.scale})", java.sql.Types.DECIMAL))
case _ => throw new IllegalArgumentException(s"Don't know how to save ${dt.json} to JDBC")
}
}
JdbcDialects.registerDialect(SQLServerDialect)
Uploading files is actually possible with AJAX these days. Yes, AJAX, not some crappy AJAX wannabes like swf or java.
This example might help you out: https://webblocks.nl/tests/ajax/file-drag-drop.html
(It also includes the drag/drop interface but that's easily ignored.)
Basically what it comes down to is this:
<input id="files" type="file" />
<script>
document.getElementById('files').addEventListener('change', function(e) {
var file = this.files[0];
var xhr = new XMLHttpRequest();
(xhr.upload || xhr).addEventListener('progress', function(e) {
var done = e.position || e.loaded
var total = e.totalSize || e.total;
console.log('xhr progress: ' + Math.round(done/total*100) + '%');
});
xhr.addEventListener('load', function(e) {
console.log('xhr upload complete', e, this.responseText);
});
xhr.open('post', '/URL-HERE', true);
xhr.send(file);
});
</script>
(demo: http://jsfiddle.net/rudiedirkx/jzxmro8r/)
So basically what it comes down to is this =)
xhr.send(file);
Where file
is typeof Blob
: http://www.w3.org/TR/FileAPI/
Another (better IMO) way is to use FormData
. This allows you to 1) name a file, like in a form and 2) send other stuff (files too), like in a form.
var fd = new FormData;
fd.append('photo1', file);
fd.append('photo2', file2);
fd.append('other_data', 'foo bar');
xhr.send(fd);
FormData
makes the server code cleaner and more backward compatible (since the request now has the exact same format as normal forms).
All of it is not experimental, but very modern. Chrome 8+ and Firefox 4+ know what to do, but I don't know about any others.
This is how I handled the request (1 image per request) in PHP:
if ( isset($_FILES['file']) ) {
$filename = basename($_FILES['file']['name']);
$error = true;
// Only upload if on my home win dev machine
if ( isset($_SERVER['WINDIR']) ) {
$path = 'uploads/'.$filename;
$error = !move_uploaded_file($_FILES['file']['tmp_name'], $path);
}
$rsp = array(
'error' => $error, // Used in JS
'filename' => $filename,
'filepath' => '/tests/uploads/' . $filename, // Web accessible
);
echo json_encode($rsp);
exit;
}
that's called colorAccent
in Android.
go to res -> values -> styles.xml add
<item name="colorAccent">#FFFFFF</item>
if not exists.
exec
is not an expression: a statement in Python 2.x, and a function in Python 3.x. It compiles and immediately evaluates a statement or set of statement contained in a string. Example:
exec('print(5)') # prints 5.
# exec 'print 5' if you use Python 2.x, nor the exec neither the print is a function there
exec('print(5)\nprint(6)') # prints 5{newline}6.
exec('if True: print(6)') # prints 6.
exec('5') # does nothing and returns nothing.
eval
is a built-in function (not a statement), which evaluates an expression and returns the value that expression produces. Example:
x = eval('5') # x <- 5
x = eval('%d + 6' % x) # x <- 11
x = eval('abs(%d)' % -100) # x <- 100
x = eval('x = 5') # INVALID; assignment is not an expression.
x = eval('if 1: x = 4') # INVALID; if is a statement, not an expression.
compile
is a lower level version of exec
and eval
. It does not execute or evaluate your statements or expressions, but returns a code object that can do it. The modes are as follows:
compile(string, '', 'eval')
returns the code object that would have been executed had you done eval(string)
. Note that you cannot use statements in this mode; only a (single) expression is valid.
compile(string, '', 'exec')
returns the code object that would have been executed had you done exec(string)
. You can use any number of statements here.
compile(string, '', 'single')
is like the exec
mode but expects exactly one expression/statement, eg compile('a=1 if 1 else 3', 'myf', mode='single')
We can add scroll bar even without using Canvas. I have read it in many other post we can't add vertical scroll bar in frame directly etc etc. But after doing many experiment found out way to add vertical as well as horizontal scroll bar :). Please find below code which is used to create scroll bar in treeView and frame.
f = Tkinter.Frame(self.master,width=3)
f.grid(row=2, column=0, columnspan=8, rowspan=10, pady=30, padx=30)
f.config(width=5)
self.tree = ttk.Treeview(f, selectmode="extended")
scbHDirSel =tk.Scrollbar(f, orient=Tkinter.HORIZONTAL, command=self.tree.xview)
scbVDirSel =tk.Scrollbar(f, orient=Tkinter.VERTICAL, command=self.tree.yview)
self.tree.configure(yscrollcommand=scbVDirSel.set, xscrollcommand=scbHDirSel.set)
self.tree["columns"] = (self.columnListOutput)
self.tree.column("#0", width=40)
self.tree.heading("#0", text='SrNo', anchor='w')
self.tree.grid(row=2, column=0, sticky=Tkinter.NSEW,in_=f, columnspan=10, rowspan=10)
scbVDirSel.grid(row=2, column=10, rowspan=10, sticky=Tkinter.NS, in_=f)
scbHDirSel.grid(row=14, column=0, rowspan=2, sticky=Tkinter.EW,in_=f)
f.rowconfigure(0, weight=1)
f.columnconfigure(0, weight=1)
you want to work onMessageReceived(RemoteMessage remoteMessage) in background send only data part notification part this:
"data": "image": "", "message": "Firebase Push Message Using API",
"AnotherActivity": "True", "to" : "device id Or Device token"
By this onMessageRecivied is call background and foreground no need to handle notification using notification tray on your launcher activity. Handle data payload in using this:
public void onMessageReceived(RemoteMessage remoteMessage)
if (remoteMessage.getData().size() > 0)
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
Although my answer is not related to datatables it addresses the issue of DOM manipulation and e.g. jQuery plugin initialization for directives used on elements which have their contents updated in async manner.
Instead of implementing a timeout one could just add a watch that will listen to content changes (or even additional external triggers).
In my case I used this workaround for initializing a jQuery plugin once the ng-repeat was done which created my inner DOM - in another case I used it for just manipulating the DOM after the scope property was altered at controller. Here is how I did ...
HTML:
<div my-directive my-directive-watch="!!myContent">{{myContent}}</div>
JS:
app.directive('myDirective', [ function(){
return {
restrict : 'A',
scope : {
myDirectiveWatch : '='
},
compile : function(){
return {
post : function(scope, element, attributes){
scope.$watch('myDirectiveWatch', function(newVal, oldVal){
if (newVal !== oldVal) {
// Do stuff ...
}
});
}
}
}
}
}]);
Note: Instead of just casting the myContent variable to bool at my-directive-watch attribute one could imagine any arbitrary expression there.
Note: Isolating the scope like in the above example can only be done once per element - trying to do this with multiple directives on the same element will result in a $compile:multidir Error - see: https://docs.angularjs.org/error/$compile/multidir
One could argue that the reasoning behind Null Object Pattern is similar to one in favour of returning the empty collection.
In general, you can create strings using:
stringExample = "someString " + str(someNumber)
print(stringExample)
plot.savefig(stringExample)
If its anywhere in the string than you can't do better than O(n).
And the only way is to search for '\n' in the string and erase it.
for(int i=0;i<s.length();i++) if(s[i]=='\n') s.erase(s.begin()+i);
For more newlines than:
int n=0;
for(int i=0;i<s.length();i++){
if(s[i]=='\n'){
n++;//we increase the number of newlines we have found so far
}else{
s[i-n]=s[i];
}
}
s.resize(s.length()-n);//to delete only once the last n elements witch are now newlines
It erases all the newlines once.
In your xml file just use a instead of the tag. The inflater tries to create an android.app.Fragment from which will fail on API < 10. So you need to create a view group of a different type.
If your method is a "regular" method and not a staticmethod
, classmethod
etc.
There is a little hack I came up with -
for k, v in your_class.__dict__.items():
if "function" in str(v):
print(k)
This can be extended to other type of methods by changing "function" in the if
condition correspondingly.
Tested in Python 2.7 and Python 3.5.
For the case XCode version is lower than iOS device's image, you can either copy the disk image from other already updated XCode(or maybe the internet) or upgrade your XCode.
The image is a folder with size about over 10MB, and place(find or put it) here under this path "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSup??port/".
To enter Xcode.app package, hold control key and click on Xcode.app, you will find additional option like show package content or some word similar. Choose this option and you will enter Xcode.app like entering a normal folder.
Hope it's helpful and good luck!
Use object keys for good performance when you work with a big array (in that case, loop for each element and loop again to check duplicate will be very slowly).
var strArray = ["q", "w", "w", "e", "i", "u", "r"];
var counting = {};
strArray.forEach(function (str) {
counting[str] = (counting[str] || 0) + 1;
});
if (Object.keys(counting).length !== strArray.length) {
console.log("Has duplicates");
var str;
for (str in counting) {
if (counting.hasOwnProperty(str)) {
if (counting[str] > 1) {
console.log(str + " appears " + counting[str] + " times");
}
}
}
}
Arrays in Java are of fixed size that is specified when they are declared. To increase the size of the array you have to create a new array with a larger size and copy all of the old values into the new array.
ex:
char[] copyFrom = { 'a', 'b', 'c', 'd', 'e' };
char[] copyTo = new char[7];
System.out.println(Arrays.toString(copyFrom));
System.arraycopy(copyFrom, 0, copyTo, 0, copyFrom.length);
System.out.println(Arrays.toString(copyTo));
Alternatively you could use a dynamic data structure like a List.
in MYSQL 5.7, max_allowed_packet
is at most 1G. if you want to set it to 4G, it would failed without error and warning.
Write below code
ImageView yourImageView = (ImageView) findViewById(R.id.yourImageView);
Bitmap bitmap = ((BitmapDrawable)yourImageView.getDrawable()).getBitmap();
You can do this with JQuery
Simply:
<form name='add'>
Age: <select id="age" name='age'>
<option value='1' stud_name='sre'>23</option>
<option value='2' stud_name='sam'>24</option>
<option value='5' stud_name='john'>25</option>
</select>
<input type='hidden' id="name" name="name" value=""/>
<input type='submit' name='submit'/>
</form>
Add this code in Header section:
<script src="http://code.jquery.com/jquery-1.9.0.min.js"></script>
Now JQuery function
<script type="text/javascript" language="javascript">
$(function() {
$("#age").change(function(){
var studentNmae= $('option:selected', this).attr('stud_name');
$('#name').val(studentNmae);
});
});
</script>
you can use both values as
$name = $_POST['name'];
$value = $_POST['age'];
exec sp_spaceused N'dbo.MyTable'
For all tables ,use..(adding from the comments of Paul)
exec sp_MSForEachTable 'exec sp_spaceused [?]'
You can create a jQuery function to unload Bootstrap CSS files at the size of 768px, and load it back when resized to lower width. This way you can design a mobile website without touching the desktop version, by using col-xs-* only
function resize() {
if ($(window).width() > 767) {
$('link[rel=stylesheet][href~="bootstrap.min.css"]').prop('disabled', true);
$('link[rel=stylesheet][href~="bootstrap-theme.min.css"]').prop('disabled', true);
}
else {
$('link[rel=stylesheet][href~="bootstrap.min.css"]').prop('disabled', false);
$('link[rel=stylesheet][href~="bootstrap-theme.min.css"]').prop('disabled', false);
}
}
and
$(document).ready(function() {
$(window).resize(resize);
resize();
if ($(window).width() > 767) {
$('link[rel=stylesheet][href~="bootstrap.min.css"]').prop('disabled', true);
$('link[rel=stylesheet][href~="bootstrap-theme.min.css"]').prop('disabled', true);
}
});
This is what I did: see on Codepen
var somedate = 1473888180593;
var myStartDate;
//var myStartDate = somedate - durationInMuntes;
myStartDate = new Date(dateAfterSubtracted('minutes', 100));
alert("The event will start on " + myStartDate.toDateString() + " at " + myStartDate.toTimeString());
function dateAfterSubtracted(range, amount){
var now = new Date();
if(range === 'years'){
return now.setDate(now.getYear() - amount);
}
if(range === 'months'){
return now.setDate(now.getMonth() - amount);
}
if(range === 'days'){
return now.setDate(now.getDate() - amount);
}
if(range === 'hours'){
return now.setDate(now.getHours() - amount);
}
if(range === 'minutes'){
return now.setDate(now.getMinutes() - amount);
}
else {
return null;
}
}
SELECT IDENT_CURRENT('databasename.dbo.tablename') AS your identity column;
I was looking for the same solution and the following worked for me.
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.clear(Calendar.HOUR);
calendar.clear(Calendar.MINUTE);
calendar.clear(Calendar.SECOND);
calendar.clear(Calendar.MILLISECOND);
Date today = calendar.getTime();
Please note that I am using calendar.set(Calendar.HOUR_OF_DAY, 0) for HOUR_OF_DAY instead of using the clear method, because it is suggested in Calendar.clear method's javadocs as the following
The HOUR_OF_DAY, HOUR and AM_PM fields are handled independently and the the resolution rule for the time of day is applied. Clearing one of the fields doesn't reset the hour of day value of this Calendar. Use set(Calendar.HOUR_OF_DAY, 0) to reset the hour value.
With the above posted solution I get output as
Wed Sep 11 00:00:00 EDT 2013
Using clear method for HOUR_OF_DAY resets hour at 12 when executing after 12PM or 00 when executing before 12PM.
It just means it expects that as a key in your header data
import requests
endpoint = ".../api/ip"
data = {"ip": "1.1.2.3"}
headers = {"Authorization": "Bearer MYREALLYLONGTOKENIGOT"}
print(requests.post(endpoint, data=data, headers=headers).json())
document.getElementById("PdfContentArea").setAttribute('data', path);
OR
var objectEl = document.getElementById("PdfContentArea")
objectEl.outerHTML = objectEl.outerHTML.replace(/data="(.+?)"/, 'data="' + path + '"');
You can bind the 'input' event to <input type="text">
. This will trigger every time the input changes such as copy, paste, keypress, and so on.
$("#input-id").on("input", function(){
// Your action
})
No.
You can use grouping selectors and/or multiple classes on a single element, or you can use a template language and process it with software to write your CSS.
See also my article on CSS inheritance.
I've had great success with this:
#include <iostream>
#include <windows.h>
int main() {
ShellExecute(NULL, "open", "path\\to\\file.exe", NULL, NULL, SW_SHOWDEFAULT);
}
If you're interested, the full documentation is here:
http://msdn.microsoft.com/en-us/library/bb762153(VS.85).aspx.
Here i have done complete bins for above query. below is demo link, i think it may help you
Demo: http://codebins.com/bin/4ldqp9b/1
HTML:
<div id="edge">
<div class="box" style="top:20; background:#f8a2a4;">
</div>
<div class="box" style="top:70; background:#a2f8a4;">
</div>
<div class="box" style="top:120; background:#5599fd;">
</div>
</div>
<br/>
<input type="button" id="btnAnimate" name="btnAnimate" value="Animate" />
CSS:
body{
background:#ffffef;
}
#edge{
width:500px;
height:200px;
border:1px solid #3377af;
padding:5px;
}
.box{
position:absolute;
left:10;
width:40px;
height:40px;
border:1px solid #a82244;
}
JQuery:
$(function() {
$("#btnAnimate").click(function() {
var move = "";
if ($(".box:eq(0)").css('left') == "10px") {
move = "+=" + ($("#edge").width() - 35);
} else {
move = "-=" + ($("#edge").width() - 35);
}
$(".box").animate({
left: move
}, 500, function() {
if ($(".box:eq(0)").css('left') == "475px") {
$(this).css('background', '#afa799');
} else {
$(".box:eq(0)").css('background', '#f8a2a4');
$(".box:eq(1)").css('background', '#a2f8a4');
$(".box:eq(2)").css('background', '#5599fd');
}
});
});
});
vertical-align:middle; text-align:right;
On CentOS Linux release 7.5.1804, we were able to make this work by editing /etc/selinux/config and changing the setting of SELINUX like so:
SELINUX=disabled
One 'elegant' solution would be to use full text search: http://www.postgresql.org/docs/9.0/interactive/textsearch.html. Then you would use full text search queries.
Use this one:
Dim ws As Worksheet
Dim range1 As Range, rng As Range
'change Sheet1 to suit
Set ws = ThisWorkbook.Worksheets("Sheet1")
Set range1 = ws.Range("A1:A5")
Set rng = ws.Range("B1")
With rng.Validation
.Delete 'delete previous validation
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Formula1:="='" & ws.Name & "'!" & range1.Address
End With
Note that when you're using Dim range1, rng As range
, only rng
has type of Range
, but range1
is Variant
. That's why I'm using Dim range1 As Range, rng As Range
.
About meaning of parameters you can read is MSDN, but in short:
Type:=xlValidateList
means validation type, in that case you should select value from listAlertStyle:=xlValidAlertStop
specifies the icon used in message boxes displayed during validation. If user enters any value out of list, he/she would get error message.Operator:= xlBetween
is odd. It can be used only if two formulas are provided for validation.Formula1:="='" & ws.Name & "'!" & range1.Address
for list data validation provides address of list with values (in format =Sheet!A1:A5
)For completeness: If you are already using the Spring framework, the StringUtils provide the method
org.springframework.util.StringUtils.hasLength(String str)
Returns: true if the String is not null and has length
as well as the method
org.springframework.util.StringUtils.hasText(String str)
Returns: true if the String is not null, its length is greater than 0, and it does not contain whitespace only
$_SERVER["PHP_SELF"];
will give you the current filename and its path, but basename(__FILE__)
should give you the filename that it is called from.
So
if(basename(__FILE__) == 'file_name.php') {
//Hide
} else {
//show
}
should do it.
For me the case was completely different. I had created a studio64.exe.vmoptions file in C:\Users\YourUserName\.AndroidStudio3.4\config. In that folder, I had a typo of extra spaces. Due to that I was getting the same error.
I replaced the studio64.exe.vmoptions with the following code.
# custom Android Studio VM options, see https://developer.android.com/studio/intro/studio-config.html
-server
-Xms1G
-Xmx8G
# I have 8GB RAM so it is 8G. Replace it with your RAM size.
-XX:MaxPermSize=1G
-XX:ReservedCodeCacheSize=512m
-XX:+UseCompressedOops
-XX:+UseConcMarkSweepGC
-XX:SoftRefLRUPolicyMSPerMB=50
-da
-Djna.nosys=true
-Djna.boot.library.path=
-Djna.debug_load=true
-Djna.debug_load.jna=true
-Dsun.io.useCanonCaches=false
-Djava.net.preferIPv4Stack=true
-XX:+HeapDumpOnOutOfMemoryError
-Didea.paths.selector=AndroidStudio2.1
-Didea.platform.prefix=AndroidStudio
This part from React v16 documentation will answer your question, read on about componentDidMount():
componentDidMount()
componentDidMount() is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request. This method is a good place to set up any subscriptions. If you do that, don’t forget to unsubscribe in componentWillUnmount().
As you see, componentDidMount is considered the best place and cycle to do the api call, also access the node, means by this time it's safe to do the call, update the view or whatever you could do when document is ready, if you are using jQuery, it should somehow remind you document.ready() function, where you could make sure everything is ready for whatever you want to do in your code...
I would say in some cases it's ok to do nothing. Probably not something you should be doing by default, but in case there should be no way for the interrupt to happen, I'm not sure what else to do (probably logging error, but that does not affect program flow).
One case would be in case you have a task (blocking) queue. In case you have a daemon Thread handling these tasks and you do not interrupt the Thread by yourself (to my knowledge the jvm does not interrupt daemon threads on jvm shutdown), I see no way for the interrupt to happen, and therefore it could be just ignored. (I do know that a daemon thread may be killed by the jvm at any time and therefore are unsuitable in some cases).
EDIT: Another case might be guarded blocks, at least based on Oracle's tutorial at: http://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html
You use something like
from flask import send_file
@app.route('/get_image')
def get_image():
if request.args.get('type') == '1':
filename = 'ok.gif'
else:
filename = 'error.gif'
return send_file(filename, mimetype='image/gif')
to send back ok.gif
or error.gif
, depending on the type query parameter. See the documentation for the send_file
function and the request
object for more information.
PHP - curl:
$username = 'myusername';
$password = 'mypassword';
...
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
...
PHP - POST in WordPress:
$username = 'myusername';
$password = 'mypassword';
...
wp_remote_post('https://...some...api...endpoint...', array(
'headers' => array(
'Authorization' => 'Basic ' . base64_encode("$username:$password")
)
));
...
If you want to use less code, you can also use the norm
in the stats
package (the 'F' stands for Forbenius, which is the Euclidean norm):
norm(matrix(x1-x2), 'F')
While this may look a bit neater, it's not faster. Indeed, a quick test on very large vectors shows little difference, though so12311's method is slightly faster. We first define:
set.seed(1234)
x1 <- rnorm(300000000)
x2 <- rnorm(300000000)
Then testing for time yields the following:
> system.time(a<-sqrt(sum((x1-x2)^2)))
user system elapsed
1.02 0.12 1.18
> system.time(b<-norm(matrix(x1-x2), 'F'))
user system elapsed
0.97 0.33 1.31
To add on to the other answers here, if you would like to create a new object of a third different type with a where clause (e.g. one that is not your Entity Framework object) you can do this:
public IEnumerable<ThirdNonEntityClass> demoMethod(IEnumerable<int> property1Values)
{
using(var entityFrameworkObjectContext = new EntityFrameworkObjectContext )
{
var result = entityFrameworkObjectContext.SomeClass
.Join(entityFrameworkObjectContext.SomeOtherClass,
sc => sc.property1,
soc => soc.property2,
(sc, soc) => new {sc, soc})
.Where(s => propertyValues.Any(pvals => pvals == es.sc.property1)
.Select(s => new ThirdNonEntityClass
{
dataValue1 = s.sc.dataValueA,
dataValue2 = s.soc.dataValueB
})
.ToList();
}
return result;
}
Pay special attention to the intermediate object that is created in the Where and Select clauses.
Note that here we also look for any joined objects that have a property1 that matches one of the ones in the input list.
I know this is a bit more complex than what the original asker was looking for, but hopefully it will help someone.
Why not to use Static Initialization Blocks
? Additional details here:
Static Initialization Blocks
You can use an anonymous function to pass the matches to your function:
$result = preg_replace_callback(
"/\{([<>])([a-zA-Z0-9_]*)(\?{0,1})([a-zA-Z0-9_]*)\}(.*)\{\\1\/\\2\}/isU",
function($m) { return CallFunction($m[1], $m[2], $m[3], $m[4], $m[5]); },
$result
);
Apart from being faster, this will also properly handle double quotes in your string. Your current code using /e
would convert a double quote "
into \"
.
You can add
DBQuery.prototype._prettyShell = true
to your file in $HOME/.mongorc.js
to enable pretty print globally by default.
to upload a file using curl in Windows I found that the path requires escaped double quotes
e.g.
curl -v -F 'upload=@\"C:/myfile.txt\"' URL
If you have a list of allowed values, you can easily retain them in an object using:
const raw = {_x000D_
item1: { key: 'sdfd', value:'sdfd' },_x000D_
item2: { key: 'sdfd', value:'sdfd' },_x000D_
item3: { key: 'sdfd', value:'sdfd' }_x000D_
};_x000D_
_x000D_
const allowed = ['item1', 'item3'];_x000D_
_x000D_
const filtered = Object.keys(raw)_x000D_
.filter(key => allowed.includes(key))_x000D_
.reduce((obj, key) => {_x000D_
obj[key] = raw[key];_x000D_
return obj;_x000D_
}, {});_x000D_
_x000D_
console.log(filtered);
_x000D_
This uses:
Object.keys
to list all properties in raw
(the original data), thenArray.prototype.filter
to select keys that are present in the allowed list, using
Array.prototype.includes
to make sure they are presentArray.prototype.reduce
to build a new object with only the allowed properties.This will make a shallow copy with the allowed properties (but won't copy the properties themselves).
You can also use the object spread operator to create a series of objects without mutating them (thanks to rjerue for mentioning this):
const raw = {_x000D_
item1: { key: 'sdfd', value:'sdfd' },_x000D_
item2: { key: 'sdfd', value:'sdfd' },_x000D_
item3: { key: 'sdfd', value:'sdfd' }_x000D_
};_x000D_
_x000D_
const allowed = ['item1', 'item3'];_x000D_
_x000D_
const filtered = Object.keys(raw)_x000D_
.filter(key => allowed.includes(key))_x000D_
.reduce((obj, key) => {_x000D_
return {_x000D_
...obj,_x000D_
[key]: raw[key]_x000D_
};_x000D_
}, {});_x000D_
_x000D_
console.log(filtered);
_x000D_
For purposes of trivia, if you wanted to remove the unwanted fields from the original data (which I would not recommend doing, since it involves some ugly mutations), you could invert the includes
check like so:
const raw = {_x000D_
item1: { key: 'sdfd', value:'sdfd' },_x000D_
item2: { key: 'sdfd', value:'sdfd' },_x000D_
item3: { key: 'sdfd', value:'sdfd' }_x000D_
};_x000D_
_x000D_
const allowed = ['item1', 'item3'];_x000D_
_x000D_
Object.keys(raw)_x000D_
.filter(key => !allowed.includes(key))_x000D_
.forEach(key => delete raw[key]);_x000D_
_x000D_
console.log(raw);
_x000D_
I'm including this example to show a mutation-based solution, but I don't suggest using it.
Solution works very well,
public List<String> savePerson(@RequestBody Person[] personArray)
For this signature you can pass Person
array from postman like
[
{
"empId": "10001",
"tier": "Single",
"someting": 6,
"anything": 0,
"frequency": "Quaterly"
}, {
"empId": "10001",
"tier": "Single",
"someting": 6,
"anything": 0,
"frequency": "Quaterly"
}
]
Don't forget to add consumes
tag:
@RequestMapping(value = "/getEmployeeList", method = RequestMethod.POST, consumes="application/json", produces = "application/json")
public List<Employee> getEmployeeDataList(@RequestBody Employee[] employeearray) { ... }
This is re-post for insert code also. This example included: - One object list - Each object hast child list. Ex:
var list1 = {
name: "Role A",
name_selected: false,
subs: [{
sub: "Read",
id: 1,
selected: false
}, {
sub: "Write",
id: 2,
selected: false
}, {
sub: "Update",
id: 3,
selected: false
}],
};
I'll 3 list like above and i'll add to a one object list
newArr.push(list1);
newArr.push(list2);
newArr.push(list3);
Then i'll do how to show checkbox with multiple group:
$scope.toggleAll = function(item) {
var toogleStatus = !item.name_selected;
console.log(toogleStatus);
angular.forEach(item, function() {
angular.forEach(item.subs, function(sub) {
sub.selected = toogleStatus;
});
});
};
$scope.optionToggled = function(item, subs) {
item.name_selected = subs.every(function(itm) {
return itm.selected;
})
$scope.txtRet = item.name_selected;
}
HTML:
<li ng-repeat="item in itemDisplayed" class="ng-scope has-pretty-child">
<div>
<ul>
<input type="checkbox" class="checkall" ng-model="item.name_selected" ng-click="toggleAll(item)"><span>{{item.name}}</span>
<div>
<li ng-repeat="sub in item.subs" class="ng-scope has-pretty-child">
<input type="checkbox" kv-pretty-check="" ng-model="sub.selected" ng-change="optionToggled(item,item.subs)"><span>{{sub.sub}}</span>
</li>
</div>
</ul>
</div>
<span>{{txtRet}}</span>
</li>
Fiddle: example
Do you want to open a shared folder in Windows Explorer? You need to use a file:
link, but there are caveats:
file://server/share/folder/
).file://///server/share/folder
) and the user has disabled the security restriction on file:
links in a page served over HTTP. Thankfully IE also accepts the mangled link form.file:
link in a page served over HTTP.Here is a code that should work in both Python 2.x and 3.x
Obviously you will need the six
module, but it's almost impossible to write modules that work in both versions without six.
try:
import configparser
except:
from six.moves import configparser
Virtual functions basically provide polymorphic behavior. That is, when you work with an object whose dynamic type is different than the static (compile time) type with which it is referred to, it provides behavior that is appropriate for the actual type of object instead of the static type of the object.
Now try to apply that sort of behavior to a constructor. When you construct an object the static type is always the same as the actual object type since:
To construct an object, a constructor needs the exact type of the object it is to create [...] Furthermore [...]you cannot have a pointer to a constructor
(Bjarne Stroustup (P424 The C++ Programming Language SE))
To adjust the length of the samples:
set key samplen X
(default is 4)
To adjust the vertical spacing of the samples:
set key spacing X
(default is 1.25)
and (for completeness), to adjust the fontsize:
set key font "<face>,<size>"
(default depends on the terminal)
And of course, all these can be combined into one line:
set key samplen 2 spacing .5 font ",8"
Note that you can also change the position of the key using set key at <position>
or any one of the pre-defined positions (which I'll just defer to help key
at this point)
This is how I do it with git v2.25.0
# requires git >= v2.25.x
git clone --no-checkout --filter=tree:0 https://github.com/opencv/opencv
cd opencv
git sparse-checkout set data/haarcascades
# or git sparse-checkout set data/haar*
# bare minimum clone of opencv
$ git clone --no-checkout --filter=tree:0 https://github.com/opencv/opencv
...
Resolving deltas: 100% (529/529), done.
# Downloaded only ~7.3MB , takes ~3 seconds
# du = disk usage, -s = summary, -h = human-readable
$ du -sh opencv
7.3M opencv/
# Set target dir
$ cd opencv
$ git sparse-checkout set data/haarcascades
...
Updating files: 100% (17/17), done.
# Takes ~10 seconds, depending on your specs
# View downloaded files
$ du -sh data/haarcascades/
9.4M data/haarcascades/
$ ls data/haarcascades/
haarcascade_eye.xml haarcascade_frontalface_alt2.xml haarcascade_licence_plate_rus_16stages.xml haarcascade_smile.xml
haarcascade_eye_tree_eyeglasses.xml haarcascade_frontalface_alt_tree.xml haarcascade_lowerbody.xml haarcascade_upperbody.xml
haarcascade_frontalcatface.xml haarcascade_frontalface_default.xml haarcascade_profileface.xml
haarcascade_frontalcatface_extended.xml haarcascade_fullbody.xml haarcascade_righteye_2splits.xml
haarcascade_frontalface_alt.xml haarcascade_lefteye_2splits.xml haarcascade_russian_plate_number.xml
Use $dec = $null
From the documentation:
$null is an automatic variable that contains a NULL or empty value. You can use this variable to represent an absent or undefined value in commands and scripts.
PowerShell treats $null as an object with a value, that is, as an explicit placeholder, so you can use $null to represent an empty value in a series of values.
If you have tried all the ways and failed, try this one command:
setsebool -P httpd_can_network_connect on
It seems that the struct
datatype is commonly used in SOAP:
var_dump($client->__getTypes());
array(52) {
[0] =>
string(43) "struct Bank {\n string Code;\n string Name;\n}"
}
This is not a native PHP datatype!
It seems that the properties of the struct
type referred to in SOAP can be accessed as a simple PHP stdClass
object:
$some_struct = $client->SomeMethod();
echo 'Name: ' . $some_struct->Name;
See the below code (taken from this post)
Put this code in a Module in VBA (Developer Tab -> Visual Basic)
Dim TimerActive As Boolean
Sub StartTimer()
Start_Timer
End Sub
Private Sub Start_Timer()
TimerActive = True
Application.OnTime Now() + TimeValue("00:01:00"), "Timer"
End Sub
Private Sub Stop_Timer()
TimerActive = False
End Sub
Private Sub Timer()
If TimerActive Then
ActiveSheet.Cells(1, 1).Value = Time
Application.OnTime Now() + TimeValue("00:01:00"), "Timer"
End If
End Sub
You can invoke the "StartTimer" function when the workbook opens and have it repeat every minute by adding the below code to your workbooks Visual Basic "This.Workbook" class in the Visual Basic editor.
Private Sub Workbook_Open()
Module1.StartTimer
End Sub
Now, every time 1 minute passes the Timer procedure will be invoked, and set cell A1 equal to the current time.
In case it's useful to anyone. For AngularJS 1.5x I wanted to set CSRF for all requests and I found that when I did this:
$httpProvider.defaults.headers.get = { 'CSRF-Token': afToken };
$httpProvider.defaults.headers.put = { 'CSRF-Token': afToken };
$httpProvider.defaults.headers.post = { 'CSRF-Token': afToken };
Angular removed the content type so I had to add this:
$httpProvider.defaults.headers.common = { "Content-Type": "application/json"};
Otherwise I get a 415 media type error.
So I am doing this to configure my application for all requests:
angular.module("myapp.maintenance", [])
.controller('maintenanceCtrl', MaintenanceCtrl)
.directive('convertToNumber', ConvertToNumber)
.config(configure);
MaintenanceCtrl.$inject = ["$scope", "$http", "$sce", "$window", "$document", "$timeout", "$filter", 'alertService'];
configure.$inject = ["$httpProvider"];
// configure the header tokens for CSRF for http operations in this module
function configure($httpProvider) {
const afToken = angular.element('input[id="__AntiForgeryToken"]').attr('value');
$httpProvider.defaults.headers.get = { 'CSRF-Token': afToken }; // only added for GET
$httpProvider.defaults.headers.put = { 'CSRF-Token': afToken }; // added for PUT
$httpProvider.defaults.headers.post = { 'CSRF-Token': afToken }; // added for POST
// for some reason if we do the above we have to set the default content type for all
// looks like angular clears it when we add our own headers
$httpProvider.defaults.headers.common = { "Content-Type": "application/json" };
}
You can type them manually but the editor will assist you.
http://developer.android.com/reference/android/Manifest.permission.html
You can see the snap sot below.
As soon as you type "a" inside the quotes you get a list of permissions and also hint to move caret up and down to select the same.
you will need to button initilzation inside method instead of trying to initlzing View's at class level do it as:
Button button; //<< declare here..
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button= (Button) findViewById(R.id.standingsButton); //<< initialize here
// set OnClickListener for Button here
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(MainActivity.this,StandingsActivity.class));
}
});
}
Under NT-style cmd.exe, you can loop through the lines of a text file with
FOR /F %i IN (file.txt) DO @echo %i
Type "help for" on the command prompt for more information. (don't know if that works in whatever "DOS" you are using)
Each argument passed via command line can be accessed with: Wscript.Arguments.Item(0) Where the zero is the argument number: ie, 0, 1, 2, 3 etc.
So in your code you could have:
strFolder = Wscript.Arguments.Item(0)
Set FSO = CreateObject("Scripting.FileSystemObject")
Set File = FSO.OpenTextFile(strFolder, 2, True)
File.Write "testing"
File.Close
Set File = Nothing
Set FSO = Nothing
Set workFolder = Nothing
Using wscript.arguments.count, you can error trap in case someone doesn't enter the proper value, etc.
Multiple inheritance allows programmers to create classes that combine aspects of multiple classes and their corresponding hierarchies. For ex. the C++ allows you to inherit from more than one class
In C#, the classes are only allowed to inherit from a single parent class, which is called single inheritance. But you can use interfaces or a combination of one class and interface(s), where interface(s) should be followed by class name in the signature.
Ex:
Class FirstClass { }
Class SecondClass { }
interface X { }
interface Y { }
You can inherit like the following:
class NewClass : X, Y { } In the above code, the class "NewClass" is created from multiple interfaces.
class NewClass : FirstClass, X { } In the above code, the class "NewClass" is created from interface X and class "FirstClass".
Oh that's easy, just use extraData
You see the way extra data works behind the scenes is the FlatList or the VirtualisedList just checks wether that object has changed via a normal onComponentWillReceiveProps
method.
So all you have to do is make sure you give something that changes to the extraData
.
Here's what I do:
I'm using immutable.js so all I do is I pass a Map (immutable object) that contains whatever I want to watch.
<FlatList
data={this.state.calendarMonths}
extraData={Map({
foo: this.props.foo,
bar: this.props.bar
})}
renderItem={({ item })=>((
<CustomComponentRow
item={item}
foo={this.props.foo}
bar={this.props.bar}
/>
))}
/>
In that way, when this.props.foo
or this.props.bar
change, our CustomComponentRow
will update, because the immutable object will be a different one than the previous.
My experience with larger files sizes has been that java.nio
is faster than java.io
. Solidly faster. Like in the >250% range. That said, I am eliminating obvious bottlenecks, which I suggest your micro-benchmark might suffer from. Potential areas for investigating:
The buffer size. The algorithm you basically have is
My own experience has been that this buffer size is ripe for tuning. I've settled on 4KB for one part of my application, 256KB for another. I suspect your code is suffering with such a large buffer. Run some benchmarks with buffers of 1KB, 2KB, 4KB, 8KB, 16KB, 32KB and 64KB to prove it to yourself.
Don't perform java benchmarks that read and write to the same disk.
If you do, then you are really benchmarking the disk, and not Java. I would also suggest that if your CPU is not busy, then you are probably experiencing some other bottleneck.
Don't use a buffer if you don't need to.
Why copy to memory if your target is another disk or a NIC? With larger files, the latency incured is non-trivial.
Like other have said, use FileChannel.transferTo()
or FileChannel.transferFrom()
. The key advantage here is that the JVM uses the OS's access to DMA (Direct Memory Access), if present. (This is implementation dependent, but modern Sun and IBM versions on general purpose CPUs are good to go.) What happens is the data goes straight to/from disc, to the bus, and then to the destination... bypassing any circuit through RAM or the CPU.
The web app I spent my days and night working on is very IO heavy. I've done micro benchmarks and real-world benchmarks too. And the results are up on my blog, have a look-see:
Use production data and environments
Micro-benchmarks are prone to distortion. If you can, make the effort to gather data from exactly what you plan to do, with the load you expect, on the hardware you expect.
My benchmarks are solid and reliable because they took place on a production system, a beefy system, a system under load, gathered in logs. Not my notebook's 7200 RPM 2.5" SATA drive while I watched intensely as the JVM work my hard disc.
What are you running on? It matters.
Howard's answer is concise and elegant, but it's also O(n^2) in the worst case. For large lists with large numbers of grouping key values, you'll want to sort the list first and then use itertools.groupby
:
>>> from itertools import groupby
>>> from operator import itemgetter
>>> seq = [["A",0], ["B",1], ["C",0], ["D",2], ["E",2]]
>>> seq.sort(key = itemgetter(1))
>>> groups = groupby(seq, itemgetter(1))
>>> [[item[0] for item in data] for (key, data) in groups]
[['A', 'C'], ['B'], ['D', 'E']]
Edit:
I changed this after seeing eyequem's answer: itemgetter(1)
is nicer than lambda x: x[1]
.
Open you working copy folder in console (terminal) and choose commands below. To see last changes: If you have commited last changes use:
svn diff -rPREV
If you left changes in working copy (that's bad practice) than use:
svn diff
To see log of commits: If you're working in branch:
svn log --stop-on-copy
If you're working with trunk:
svn log | head
or just
svn log
I'm not so thrilled about the InetAddress.getLocalHost().getHostName()
solution that you can find so many places on the Internet and indeed also here. That method will get you the hostname as seen from a network perspective. I can see two problems with this:
What if the host has multiple network interfaces ? The host may be known on the network by multiple names. The one returned by said method is indeterminate afaik.
What if the host is not connected to any network and has no network interfaces ?
All OS'es that I know of have the concept of naming a node/host irrespective of network. Sad that Java cannot return this in an easy way. This would be the environment variable COMPUTERNAME
on all versions of Windows and the environment variable HOSTNAME
on Unix/Linux/MacOS (or alternatively the output from host command hostname
if the HOSTNAME
environment variable is not available as is the case in old shells like Bourne and Korn).
I would write a method that would retrieve (depending on OS) those OS vars and only as a last resort use the InetAddress.getLocalHost().getHostName()
method. But that's just me.
As others have pointed out the HOSTNAME
environment variable is typically not available to a Java application on Unix/Linux as it is not exported by default. Hence not a reliable method unless you are in control of the clients. This really sucks. Why isn't there a standard property with this information?
Alas, as far as I can see the only reliable way on Unix/Linux would be to make a JNI call to gethostname() or to use Runtime.exec()
to capture the output from the hostname
command. I don't particularly like any of these ideas but if anyone has a better idea I'm all ears. (update: I recently came across gethostname4j which seems to be the answer to my prayers).
I've created a long explanation in another answer on another post. In particular you may want to read it because it attempts to establish some terminology, gives concrete examples of when the InetAddress.getLocalHost().getHostName()
solution will fail, and points to the only safe solution that I know of currently, namely gethostname4j.
It's sad that Java doesn't provide a method for obtaining the computername. Vote for JDK-8169296 if you are able to.
With ES2015 you can use this one:
Array.prototype.shuffle = function() {
let m = this.length, i;
while (m) {
i = (Math.random() * m--) >>> 0;
[this[m], this[i]] = [this[i], this[m]]
}
return this;
}
Usage:
[1, 2, 3, 4, 5, 6, 7].shuffle();
You can read about jQuery Ajax from official jQuery Site: https://api.jquery.com/jQuery.ajax/
If you don't want to use any click event then you can set timer for periodically update.
Below code may be help you just example.
function update() {
$.get("response.php", function(data) {
$("#some_div").html(data);
window.setTimeout(update, 10000);
});
}
Above function will call after every 10 seconds and get content from response.php and update in #some_div
.
Example code using NLog that will catch exceptions thrown from all threads in the AppDomain, from the UI dispatcher thread and from the async functions:
public partial class App : Application
{
private static Logger _logger = LogManager.GetCurrentClassLogger();
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
SetupExceptionHandling();
}
private void SetupExceptionHandling()
{
AppDomain.CurrentDomain.UnhandledException += (s, e) =>
LogUnhandledException((Exception)e.ExceptionObject, "AppDomain.CurrentDomain.UnhandledException");
DispatcherUnhandledException += (s, e) =>
{
LogUnhandledException(e.Exception, "Application.Current.DispatcherUnhandledException");
e.Handled = true;
};
TaskScheduler.UnobservedTaskException += (s, e) =>
{
LogUnhandledException(e.Exception, "TaskScheduler.UnobservedTaskException");
e.SetObserved();
};
}
private void LogUnhandledException(Exception exception, string source)
{
string message = $"Unhandled exception ({source})";
try
{
System.Reflection.AssemblyName assemblyName = System.Reflection.Assembly.GetExecutingAssembly().GetName();
message = string.Format("Unhandled exception in {0} v{1}", assemblyName.Name, assemblyName.Version);
}
catch (Exception ex)
{
_logger.Error(ex, "Exception in LogUnhandledException");
}
finally
{
_logger.Error(exception, message);
}
}
I have also faced this problem.Double check the result in the error window.
In my case, a tailing \
was crashing xcopy (as I was using $(TargetDir)
). In my case $(SolutionDir)..\bin
. If you're using any other output, this needs to be adjusted.
Also note that start xcopy
does not fix it, if the error is gone after compiling. It might have just been suppressed by the command line and no file has actually been copied!
You can btw manually execute your xcopy commands in a command shell. You will get more details when executing them there, pointing you in the right direction.
Spring Boot allows you to use a simple script to initialize your database, using Spring Batch.
Still, if you want to use something a bit more elaborated to manage DB versions and so on, Spring Boot integrates well with Flyway.
See also:
With pygame
so this should work as I tested (you have to have pygame installed if you do not have pygame install it by using pip -> pip install pygame (that sometimes does not work so in that case you will have to download the wheel or sth but that you can look up on google)):
import pygame
pygame.init()
win = pygame.display.set_mode((128, 128))
pygame.surfarray.blit_array(win, yourarray)
pygame.display.update()
pygame.image.save(win, 'yourfilename.png')
just remember to change display width and height according to your array
here is an example, run this code:
import pygame
from numpy import zeros
pygame.init()
win = pygame.display.set_mode((128, 128))
striped = zeros((128, 128, 3))
striped[:] = (255, 0, 0)
striped[:, ::3] = (0, 255, 255)
pygame.surfarray.blit_array(win, striped)
pygame.display.update()
pygame.image.save(win, 'yourfilename.png')
(a–b)/c*(d + e – f / g)
Prefix notation (reverse polish has the operator last, it is unclear which one you meant, but the principle will be exactly the same):
(/ f g)
(+ d e)
(- (+ d e) (/ f g))
(- a b)
(/ (- a b) c)
(* (/ (- a b) c) (- (+ d e) (/ f g)))
Set IFS to newline, like this:
IFS='
'
for x in `ls -l $1`; do echo $x; done
Put a sub-shell around it if you don't want to set IFS permanently:
(IFS='
'
for x in `ls -l $1`; do echo $x; done)
Or use while | read instead:
ls -l $1 | while read x; do echo $x; done
One more option, which runs the while/read at the same shell level:
while read x; do echo $x; done << EOF
$(ls -l $1)
EOF
override func didMoveToParentViewController(parent: UIViewController?) {
if parent == nil {
//"Back pressed"
}
}
This code worked for me
public static void main(String[] args) {
try {
java.net.URL myUr = new java.net.URL("http://path");
System.out.println("Instantiated new URL: " + connection_url);
}
catch (MalformedURLException e) {
e.printStackTrace();
}
}
Instantiated new URL: http://path
Open them from a new instance of Excel.
Sub Test()
Dim xl As Excel.Application
Set xl = CreateObject("Excel.Application")
Dim w As Workbook
Set w = xl.Workbooks.Add()
MsgBox "Not visible yet..."
xl.Visible = True
w.Close False
Set xl = Nothing
End Sub
You need to remember to clean up after you're done.
Add following Spark dependencies to POM file :
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-core_2.11</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-sql_2.11</artifactId>
<version>2.2.0</version>
</dependency>
//Spark configuration:
val spark = SparkSession.builder().master("local").appName("Sample App").getOrCreate()
//Read csv file:
val df = spark.read.option("header", "true").csv("FILE_PATH")
// Display output
df.show()
Unfortunately, no. Not with HTML and CSS. You need an a
element to make a link, and you can't wrap an entire table row in one.
The closest you can get is linking every table cell. Personally I'd just link one cell and use JavaScript to make the rest clickable. It's good to have at least one cell that really looks like a link, underlined and all, for clarity anyways.
Here's a simple jQuery snippet to make all table rows with links clickable (it looks for the first link and "clicks" it)
$("table").on("click", "tr", function(e) {
if ($(e.target).is("a,input")) // anything else you don't want to trigger the click
return;
location.href = $(this).find("a").attr("href");
});
I found one Solution :
echo iconv('UTF-8', 'ASCII//TRANSLIT', utf8_encode($string));
use utf8_encode()
Python has three modes via., private, public and protected .While importing a module only public mode is accessible .So private and protected modules cannot be called from outside of the module i.e., when it is imported .
Very nice pdf about many GIT secrets.
Add is same as svn's add (how ever sometimes it is used to mark file resolved).
Commit also is same as svn's , but it commit change into your local repository.
Here is how to do it using the XML features of DB2
SELECT *
FROM
XMLTABLE ('$doc/ROWSET/ROW' PASSING XMLPARSE ( DOCUMENT '
<ROWSET>
<ROW>
<A val="1" /> <B val="2" /> <C val="3" />
</ROW>
<ROW>
<A val="4" /> <B val="5" /> <C val="6" />
</ROW>
<ROW>
<A val="7" /> <B val="8" /> <C val="9" />
</ROW>
</ROWSET>
') AS "doc"
COLUMNS
"A" INT PATH 'A/@val',
"B" INT PATH 'B/@val',
"C" INT PATH 'C/@val'
)
AS X
;
React Native
These steps solved my problem:
** It's quite interesting to close Android Studio. But beleive me these steps solved my problem **
I know it's been a while on this question, but I was just looking for the same answer and found this seems to be the simplest solution:
select * from sales where datediff(dd, salesDate, '20101111') = 0
I actually use it more to find things within the last day or two, so my version looks like this:
select * from sales where datediff(dd, salesDate, getdate()) = 0
And by changing the 0 for today to a 1 I get yesterday's transactions, 2 is the day before that, and so on. And if you want everything for the last week, just change the equals to a less-than-or-equal-to:
select * from sales where datediff(dd, salesDate, getdate()) <= 7
Look into using the ToString()
method with a specified format.
Sounds like you're calling df.plot()
. That error indicates that you're trying to plot a frame that has no numeric data. The data types shouldn't affect what you print()
.
Use print(df.iloc[159220])
The C++ way of solving conversions (not the classical C) is illustrated with the program below. Note that the intent is to be able to use the same formatting facilities offered by iostream like precision, fill character, padding, hex, and the manipulators, etcetera.
Compile and run this program, then study it. It is simple
#include "iostream"
#include "iomanip"
#include "sstream"
using namespace std;
int main()
{
// Converting the content of a char array or a string to a double variable
double d;
string S;
S = "4.5";
istringstream(S) >> d;
cout << "\nThe value of the double variable d is " << d << endl;
istringstream("9.87654") >> d;
cout << "\nNow the value of the double variable d is " << d << endl;
// Converting a double to string with formatting restrictions
double D=3.771234567;
ostringstream Q;
Q.fill('#');
Q << "<<<" << setprecision(6) << setw(20) << D << ">>>";
S = Q.str(); // formatted converted double is now in string
cout << "\nThe value of the string variable S is " << S << endl;
return 0;
}
Prof. Martinez
You can also define a textvariable
when creating the Label, and change the textvariable to update the text in the label.
Here's an example:
labelText = Stringvar()
depositLabel = Label(self, textvariable=labelText)
depositLabel.grid()
def updateDepositLabel(txt) # you may have to use *args in some cases
labelText.set(txt)
There's no need to update the text in depositLabel
manually. Tk does that for you.
Steps:
Tip:
I've also been successful with this URL structure:
Base URL:
https://calendar.google.com/calendar/r/eventedit?
And let's say this is my event details:
Title: Event Title
Description: Example of some description. See more at https://stackoverflow.com/questions/10488831/link-to-add-to-google-calendar
Location: 123 Some Place
Date: February 22, 2020
Start Time: 10:00am
End Time: 11:30am
Timezone: America/New York (GMT -5)
I'd convert my details into these parameters (URL encoded):
text=Event%20Title
details=Example%20of%20some%20description.%20See%20more%20at%20https%3A%2F%2Fstackoverflow.com%2Fquestions%2F10488831%2Flink-to-add-to-google-calendar
location=123%20Some%20Place%2C%20City
dates=20200222T100000/20200222T113000
ctz=America%2FNew_York
Example link:
Please note that since I've specified a timezone with the "ctz" parameter, I used the local times for the start and end dates. Alternatively, you can use UTC dates and exclude the timezone parameter, like this:
dates=20200222T150000Z/20200222T163000Z
Example link:
Much better way to limit the range... used the contains logic from above poster.
var dragStartCenter;
google.maps.event.addListener(map, 'dragstart', function(){
dragStartCenter = map.getCenter();
});
google.maps.event.addListener(this.googleMap, 'dragend', function(){
if (mapBounds.contains(map.getCenter())) return;
map.setCenter(this.dragStart);
});
The code below works with Last, First M name strings. Substitute "Name" with your name string column name. Since you have a period as a final character when there is a middle initial, you would replace the 2's with 3's in each of the lines (2, 6, and 8)- and change "RIGHT(Name, 1)" to "RIGHT(Name, 2)" in line 8.
SELECT SUBSTRING(Name, 1, CHARINDEX(',', Name) - 1) LastName ,
CASE WHEN LEFT(RIGHT(Name, 2), 1) <> ' '
THEN LTRIM(SUBSTRING(Name, CHARINDEX(',', Name) + 1, 99))
ELSE LEFT(LTRIM(SUBSTRING(Name, CHARINDEX(',', Name) + 1, 99)),
LEN(LTRIM(SUBSTRING(Name, CHARINDEX(',', Name) + 1, 99)))
- 2)
END FirstName ,
CASE WHEN LEFT(RIGHT(Name, 2), 1) = ' ' THEN RIGHT(Name, 1)
ELSE NULL
END MiddleName
I had similar expirience like yours. I have Denwer server. When I loaded my http://new.new local site without using via script src jquery.min.js file at index.php in Chrome I got error 500 jquery.min.map in console. I resolved this problem simply - I disabled extension Wunderlist in Chrome and voila - I never see this error more. Although, No, I found this error again - when Wunderlist have been on again. So, check your extensions and try to disable all of them or some of them or one by one. Good luck!
In my case the targetPath
was not having any value it was blank in the resources --> resource
for the file directory
with files that had issue.
I had to update it to global
as seen in the Code Sample 2
and re-run build to fix the issue.
Code Sample 1 (with issue)
<build>
<resources>
<resource>
<directory>src/main/locale</directory>
<filtering>true</filtering>
<targetPath></targetPath>
<includes>
<include>*.xml</include>
<include>*.config</include>
<include>*.properties</include>
</includes>
</resource>
</resources>
Code Sample 2 (fix applied)
<build>
<resources>
<resource>
<directory>src/main/locale</directory>
<filtering>true</filtering>
<targetPath>global</targetPath>
<includes>
<include>*.xml</include>
<include>*.config</include>
<include>*.properties</include>
</includes>
</resource>
</resources>
Am afraid this question has been answered a few times, Pls take a look at the following if it's related
For me, when typing the url, a user accidentally used a / instead of a ? to start the query parameters
e.g.:
url.com/endpoint/parameter=SomeValue&otherparameter=Another+value
which should have been:
url.com/endpoint?parameter=SomeValue&otherparameter=Another+value
I own a mac too! here is the code that will work:
myButton.setBackground(Color.RED);
myButton.setOpaque(true); //Sets Button Opaque so it works
before doing anything or adding any components set the look and feel so it looks better:
try{
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
}catch(Exception e){
e.printStackTrace();
}
That is Supposed to change the look and feel to the cross platform look and feel, hope i helped! :)
You can change the last line to following (assuming you want to return 0 when there is nothing in db):
return OrdersPerHour == null ? 0 : OrdersPerHour.Value;
You need to add a name
attribute to your dropdown list, then you need to add a required
attribute, and then you can reference the error using myForm.[input name].$error.required
:
HTML:
<form name="myForm" ng-controller="Ctrl" ng-submit="save(myForm)" novalidate>
<input type="text" name="txtServiceName" ng-model="ServiceName" required>
<span ng-show="myForm.txtServiceName.$error.required">Enter Service Name</span>
<br/>
<select name="service_id" class="Sitedropdown" style="width: 220px;"
ng-model="ServiceID"
ng-options="service.ServiceID as service.ServiceName for service in services"
required>
<option value="">Select Service</option>
</select>
<span ng-show="myForm.service_id.$error.required">Select service</span>
</form>
Controller:
function Ctrl($scope) {
$scope.services = [
{ServiceID: 1, ServiceName: 'Service1'},
{ServiceID: 2, ServiceName: 'Service2'},
{ServiceID: 3, ServiceName: 'Service3'}
];
$scope.save = function(myForm) {
console.log('Selected Value: '+ myForm.service_id.$modelValue);
alert('Data Saved! without validate');
};
}
Here's a working plunker.
(MyColours)Enum.Parse(typeof(MyColours), "red", true); // MyColours.Red
(int)((MyColours)Enum.Parse(typeof(MyColours), "red", true)); // 0
Use this Layout in your xml file
<LinearLayout
android:id="@+id/contacts_type"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone">
</LinearLayout>
Define your layout in .class file
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.contacts_type);
Now if you want to display this layout just write
linearLayout.setVisibility(View.VISIBLE);
and if you want to hide layout just write
linearLayout.setVisibility(View.INVISIBLE);
Sample:
Label label = new Label();
label.HorizontalContentAlignment = HorizontalAlignment.Center;
Here is an alternative method for doing multiple args. I use it when the arguments are too long for a one liner.
$app = 'C:\Program Files\MSBuild\test.exe'
$arg1 = '/genmsi'
$arg2 = '/f'
$arg3 = '$MySourceDirectory\src\Deployment\Installations.xml'
& $app $arg1 $arg2 $arg3
Working fine after removing the Android Wear ARM EABI v7a system image and wear intel x86 Atom System image.
In [30]: pd.Series([1,2,3,4,'.']).convert_objects(convert_numeric=True)
Out[30]:
0 1
1 2
2 3
3 4
4 NaN
dtype: float64
Based on the previous answers I'm using the following utility methods in case anyone would like to use it.
/**
* @param message the message to be encoded
*
* @return the enooded from of the message
*/
public static String toBase64(String message) {
byte[] data;
try {
data = message.getBytes("UTF-8");
String base64Sms = Base64.encodeToString(data, Base64.DEFAULT);
return base64Sms;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
/**
* @param message the encoded message
*
* @return the decoded message
*/
public static String fromBase64(String message) {
byte[] data = Base64.decode(message, Base64.DEFAULT);
try {
return new String(data, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
In my situation the cause was that I had ran Visual Studio as an administrator earlier in the day. When I went to switch branches the error occurred.
I use GitExtensions and I run it as a regular users and files created by VS while running as an administrator ( run as Administrator, still me though) were not accessible. This was the root of the cause for me. I'm not sure why it happened in this situation because I regularly run VS as administrator on my primary development environment and have not experienced this problem before. But for some reason today the above scenario caused any files generated by VS during that session to be un-editable...you can read them, but not change or delete them and that is exactly what Git is going to do when you switch branches.
To resolve the problem for Git I had to start windows explorer as administrator and take ownership and re give myself permissions to files and directories in question. I don't fully understand why this as I was running explorer as Administrator too but it did.
You can do this for the files individually but I ended up doing this process for the root folder of the branch.
So the exact steps I did to fix the problem are: Went to the top of the branch in windows explorer, right clicked properties of the directory, select the security tab, advanced options which opens the Advanced Security Settings dialog, Selected change ownership at the top (it might show you already own it), I re-selected myself. Then it returns you to the 'Advanced Security Settings' dialog, at the bottom of remember to check the box 'Replace all object...' Then click apply The system cycles through each file and folder fixing ownership and that resolved the problem for me.
For me it had locked out my migrations folder and wouldn't let me switch branches...so I originally just fixed that directory and sub tree which allowed me to switch branches but I had closed VS trying to resolved the issue. When I reopened VS I did not run VS as the Administrator and I found that could not compile the solution now! It was the same\similar issue. It could not compile the solution as all of the obj directories were now non editable... so that is when I did the above steps and all was good again.
Hope this helps someone... ;)
Multiple things can cause this, I didn't bother to check your entire repository, so I'm going out on a limb here.
First off, you could be missing an annotation (@Service or @Component) from the implementation of com.example.my.services.user.UserService
, if you're using annotations for configuration. If you're using (only) xml, you're probably missing the <bean>
-definition for the UserService-implementation.
If you're using annotations and the implementation is annotated correctly, check that the package where the implementation is located in is scanned (check your <context:component-scan base-package=
-value).
This might be because you are using two method for inserting data into database and this cause the site to slow down.
def add_subscriber(request, email=None):
if request.method == 'POST':
email = request.POST['email_field']
e = Subscriber.objects.create(email=email).save() <====
return HttpResponseRedirect('/')
else:
return HttpResponseRedirect('/')
In above function, the error is where arrow is pointing. The correct implementation is below:
def add_subscriber(request, email=None):
if request.method == 'POST':
email = request.POST['email_field']
e = Subscriber.objects.create(email=email)
return HttpResponseRedirect('/')
else:
return HttpResponseRedirect('/')
Beginning PowerShell 5.0 New-Item
, Remove-Item
, and Get-ChildItem
have been enhanced to support creating and managing symbolic links. The ItemType parameter for New-Item
accepts a new value, SymbolicLink. Now you can create symbolic links in a single line by running the New-Item cmdlet.
New-Item -ItemType SymbolicLink -Path "C:\temp" -Name "calc.lnk" -Value "c:\windows\system32\calc.exe"
Be Carefull a SymbolicLink is different from a Shortcut, shortcuts are just a file. They have a size (A small one, that just references where they point) and they require an application to support that filetype in order to be used. A symbolic link is filesystem level, and everything sees it as the original file. An application needs no special support to use a symbolic link.
Anyway if you want to create a Run As Administrator shortcut using Powershell you can use
$file="c:\temp\calc.lnk"
$bytes = [System.IO.File]::ReadAllBytes($file)
$bytes[0x15] = $bytes[0x15] -bor 0x20 #set byte 21 (0x15) bit 6 (0x20) ON (Use –bor to set RunAsAdministrator option and –bxor to unset)
[System.IO.File]::WriteAllBytes($file, $bytes)
If anybody want to change something else in a .LNK file you can refer to official Microsoft documentation.
Whenever I have to do it, mostly while communicating json schema and constants with the frontend I define a class as follows
class Param:
def __init__(self, name, value):
self.name = name
self.value = value
Then define the variable with name and value.
frame_folder_count = Param({'name':'frame_folder_count', 'value':10})
Now you can access the name and value using the object.
>>> frame_folder_count.name
'frame_folder_count'
For only one line, you need
...
<View android:id="@+id/primerdivisor"
android:layout_height="2dp"
android:layout_width="fill_parent"
android:background="#ffffff" />
...
i solved this issue after more Study...
for Api21 and more use
<item name="android:textColorPrimary">@color/white</item>
for Lower versions use
<item name="actionMenuTextColor">@color/white</item>
Replace '+' with '000'. For example, 'U+1F600' will become 'U0001F600' and prepend the Unicode code with "\" and print. Example:
>>> print("Learning : ", "\U0001F40D")
Learning :
>>>
Check this maybe it will help python unicode emoji
With the release of Cordova 3.3.0, it seems the PhoneGap team is trying to address the naming confusion. The documentations have been updated to recommend people using the cordova
command instead. Do not use the command anymore.phonegap
Here is a fresh installation guide for a guaranteed trouble free set up:
Install Cordova (forget the name PhoneGap from now on). For PC:
C:> npm install -g cordova
From command prompt, navigate to the folder you want to create your project using:
cordova create hello com.example.hello HelloWorld cd hello
Define the OS you want to suppport for example:
cordova platform add wp8
Install plugins (If needed). For example we want the following:
cordova plugin add org.apache.cordova.device cordova plugin add org.apache.cordova.camera cordova plugin add org.apache.cordova.media-capture cordova plugin add org.apache.cordova.media
cordova build wp8
Here is a link to the PhoneGapCordova 3.3.0 Documentation
http://docs.phonegap.com/en/3.3.0/guide_cli_index.md.html#The%20Command-Line%20Interface
I wrote a tool to capture images from a webcam entirely in Python, based on DirectShow. You can find it here: https://github.com/andreaschiavinato/python_grabber.
You can use the whole application or just the class FilterGraph in dshow_graph.py in the following way:
from pygrabber.dshow_graph import FilterGraph
import numpy as np
from matplotlib.image import imsave
graph = FilterGraph()
print(graph.get_input_devices())
device_index = input("Enter device number: ")
graph.add_input_device(int(device_index))
graph.display_format_dialog()
filename = r"c:\temp\imm.png"
# np.flip(image, axis=2) required to convert image from BGR to RGB
graph.add_sample_grabber(lambda image : imsave(filename, np.flip(image, axis=2)))
graph.add_null_render()
graph.prepare()
graph.run()
x = input("Press key to grab photo")
graph.grab_frame()
x = input(f"File {filename} saved. Press key to end")
graph.stop()
chmod +x gradlew
Just run the above comment. that's all enjoy your coding...
In addition to DannySmurf's answer of laziness, I'll add that it's to encourage you to use the constants, such as Calendar.JANUARY
.
It can be due to psql not being in PATH
$ locate psql
/usr/lib/postgresql/9.6/bin/psql
Then create a link in /usr/bin
ln -s /usr/lib/postgresql/9.6/bin/psql /usr/bin/psql
Then try to execute psql it should work.
While some of the proposed solutions work for fragment links (= hash links) within the same page (like a menu link that scrolls down), I found that none of them worked in current Chrome when you want to use fragment links coming in from other pages.
So calling www.mydomain.com/page.html#foo from scratch will NOT offset your target in current Chrome with any of the given CSS solutions or JS solutions.
There is also a jQuery bug report describing some details of the problem.
SOLUTION
The only option I found so far that really works in Chrome is JavaScript that is not called onDomReady but with a delay.
// set timeout onDomReady
$(function() {
setTimeout(delayedFragmentTargetOffset, 500);
});
// add scroll offset to fragment target (if there is one)
function delayedFragmentTargetOffset(){
var offset = $(':target').offset();
if(offset){
var scrollto = offset.top - 95; // minus fixed header height
$('html, body').animate({scrollTop:scrollto}, 0);
}
}
SUMMARY
Without a JS delay solutions will probably work in Firefox, IE, Safari, but not in Chrome.
The previous answers have properly explained the way to create a configuration file to manage multiple ssh keys. I think, the important thing that also needs to be explained is the replacement of a host name with an alias name while cloning the repository.
Suppose, your company's GitHub account's username is abc1234. And suppose your personal GitHub account's username is jack1234
And, suppose you have created two RSA keys, namely id_rsa_company and id_rsa_personal. So, your configuration file will look like below:
# Company account
Host company
HostName github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_company
# Personal account
Host personal
HostName github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_personal
Now, when you are cloning the repository (named demo) from the company's GitHub account, the repository URL will be something like:
Repo URL: [email protected]:abc1234/demo.git
Now, while doing git clone
, you should modify the above repository URL as:
git@company:abc1234/demo.git
Notice how github.com is now replaced with the alias "company" as we have defined in the configuration file.
Similary, you have to modify the clone URL of the repository in the personal account depending upon the alias provided in the configuration file.
The data returned by the JSON is in json format : which is simply an arrays of values. Thats why you are seeing [object Object],[object Object],[object Object].
You have to iterate through that values to get actuall value. Like the following
jQuery provides $.each() for iterations, so you could also do this:
$.getJSON("url_with_json_here", function(data){
$.each(data, function (linktext, link) {
console.log(linktext);
console.log(link);
});
});
Now just create an Hyperlink using that info.