On Android, network operations cannot be run on the main thread. You can use Thread
, AsyncTask
(short-running tasks), Service
(long-running tasks) to do network operations. android.os.NetworkOnMainThreadException
is thrown when an application attempts to perform a networking operation on its main thread. If your task took above five seconds, it takes a force close.
Run your code in AsyncTask
:
class FeedTask extends AsyncTask<String, Void, Boolean> {
protected RSSFeed doInBackground(String... urls) {
// TODO: Connect
}
protected void onPostExecute(RSSFeed feed) {
// TODO: Check this.exception
// TODO: Do something with the feed
}
}
OR
new Thread(new Runnable(){
@Override
public void run() {
try {
// Your implementation
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}).start();
This is not recommended. But for DEBUG purpose you can disable the strict mode as well using the following code:
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy =
new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
I made an extension function for Kotlin. Paste it where ever you like and import it while creating OkHttpClient
.
fun OkHttpClient.Builder.ignoreAllSSLErrors(): OkHttpClient.Builder {
val naiveTrustManager = object : X509TrustManager {
override fun getAcceptedIssuers(): Array<X509Certificate> = arrayOf()
override fun checkClientTrusted(certs: Array<X509Certificate>, authType: String) = Unit
override fun checkServerTrusted(certs: Array<X509Certificate>, authType: String) = Unit
}
val insecureSocketFactory = SSLContext.getInstance("TLSv1.2").apply {
val trustAllCerts = arrayOf<TrustManager>(naiveTrustManager)
init(null, trustAllCerts, SecureRandom())
}.socketFactory
sslSocketFactory(insecureSocketFactory, naiveTrustManager)
hostnameVerifier(HostnameVerifier { _, _ -> true })
return this
}
use it like this:
val okHttpClient = OkHttpClient.Builder().apply {
// ...
if (BuildConfig.DEBUG) //if it is a debug build ignore ssl errors
ignoreAllSSLErrors()
//...
}.build()
Answer to your first question: Your broadcast receiver is being called two times because
You have added two <intent-filter>
Change in network connection :
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
Change in WiFi state:
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
Just use one:
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
.
It will respond to only one action instead of two. See here for more information.
Answer to your second question (you want receiver to call only one time if internet connection available):
Your code is perfect; you notify only when internet is available.
UPDATE
You can use this method to check your connectivity if you want just to check whether mobile is connected with the internet or not.
public boolean isOnline(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
//should check null because in airplane mode it will be null
return (netInfo != null && netInfo.isConnected());
}
No need to be complex. The simplest and framework manner is to use ACCESS_NETWORK_STATE
permission and just make a connected method
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnectedOrConnecting();
}
You can also use requestRouteToHost
if you have a particualr host and connection type (wifi/mobile) in mind.
You will also need:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
in your android manifest.
for more detail go here
I've recently found a lib called ion that brings a little extra to the table.
ion has built-in support for image download integrated with ImageView, JSON (with the help of GSON), files and a very handy UI threading support.
I'm using it on a new project and so far the results have been good. Its use is much simpler than Volley or Retrofit.
You need to do it through an ArrayAdapter
which will adapt your ArrayList (or any other collection) to your items in your layout (ListView, Spinner etc.).
This is what the Android developer guide says:
A
ListAdapter
that manages aListView
backed by an array of arbitrary objects. By default this class expects that the provided resource id references a singleTextView
. If you want to use a more complex layout, use the constructors that also takes a field id. That field id should reference aTextView
in the larger layout resource.However the
TextView
is referenced, it will be filled with thetoString()
of each object in the array. You can add lists or arrays of custom objects. Override thetoString()
method of your objects to determine what text will be displayed for the item in the list.To use something other than
TextViews
for the array display, for instanceImageViews
, or to have some of data besidestoString()
results fill the views, overridegetView(int, View, ViewGroup)
to return the type of view you want.
So your code should look like:
public class YourActivity extends Activity {
private ListView lv;
public void onCreate(Bundle saveInstanceState) {
setContentView(R.layout.your_layout);
lv = (ListView) findViewById(R.id.your_list_view_id);
// Instanciating an array list (you don't need to do this,
// you already have yours).
List<String> your_array_list = new ArrayList<String>();
your_array_list.add("foo");
your_array_list.add("bar");
// This is the array adapter, it takes the context of the activity as a
// first parameter, the type of list view as a second parameter and your
// array as a third parameter.
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
your_array_list );
lv.setAdapter(arrayAdapter);
}
}
Self invoked function in javascript:
A self-invoking expression is invoked (started) automatically, without being called. A self-invoking expression is invoked right after its created. This is basically used for avoiding naming conflict as well as for achieving encapsulation. The variables or declared objects are not accessible outside this function. For avoiding the problems of minimization(filename.min) always use self executed function.
According to the principle of separation:
Auditing data tables need to be separate from the main database. Because audit databases can have a lot of historical data, it makes sense from a memory utilization standpoint to keep them separate.
Do not use triggers to audit the whole database, because you will end up with a mess of different databases to support. You will have to write one for DB2, SQLServer, Mysql, etc.
since my post above, I have moved to a Generic Factory Class
Usage
services.AddFactory<IProcessor, string>()
.Add<ProcessorA>("A")
.Add<ProcessorB>("B");
public MyClass(IFactory<IProcessor, string> processorFactory)
{
var x = "A"; //some runtime variable to select which object to create
var processor = processorFactory.Create(x);
}
Implementation
public class FactoryBuilder<I, P> where I : class
{
private readonly IServiceCollection _services;
private readonly FactoryTypes<I, P> _factoryTypes;
public FactoryBuilder(IServiceCollection services)
{
_services = services;
_factoryTypes = new FactoryTypes<I, P>();
}
public FactoryBuilder<I, P> Add<T>(P p)
where T : class, I
{
_factoryTypes.ServiceList.Add(p, typeof(T));
_services.AddSingleton(_factoryTypes);
_services.AddTransient<T>();
return this;
}
}
public class FactoryTypes<I, P> where I : class
{
public Dictionary<P, Type> ServiceList { get; set; } = new Dictionary<P, Type>();
}
public interface IFactory<I, P>
{
I Create(P p);
}
public class Factory<I, P> : IFactory<I, P> where I : class
{
private readonly IServiceProvider _serviceProvider;
private readonly FactoryTypes<I, P> _factoryTypes;
public Factory(IServiceProvider serviceProvider, FactoryTypes<I, P> factoryTypes)
{
_serviceProvider = serviceProvider;
_factoryTypes = factoryTypes;
}
public I Create(P p)
{
return (I)_serviceProvider.GetService(_factoryTypes.ServiceList[p]);
}
}
Extension
namespace Microsoft.Extensions.DependencyInjection
{
public static class DependencyExtensions
{
public static FactoryBuilder<I, P> AddFactory<I, P>(this IServiceCollection services)
where I : class
{
services.AddTransient<IFactory<I, P>, Factory<I, P>>();
return new FactoryBuilder<I, P>(services);
}
}
}
In case you're using ASP.NET 5 with ASP.NET MVC 6, most of these answers simply won't work because you'll normally let MVC create the appropriate route collection for you (using the default RESTful conventions), meaning that you won't find any Routes.MapRoute()
call to edit at will.
The ConfigureServices()
method invoked by the Startup.cs
file will register MVC with the Dependency Injection framework built into ASP.NET 5: that way, when you call ApplicationBuilder.UseMvc()
later in that class, the MVC framework will automatically add these default routes to your app. We can take a look of what happens behind the hood by looking at the UseMvc()
method implementation within the framework source code:
public static IApplicationBuilder UseMvc(
[NotNull] this IApplicationBuilder app,
[NotNull] Action<IRouteBuilder> configureRoutes)
{
// Verify if AddMvc was done before calling UseMvc
// We use the MvcMarkerService to make sure if all the services were added.
MvcServicesHelper.ThrowIfMvcNotRegistered(app.ApplicationServices);
var routes = new RouteBuilder
{
DefaultHandler = new MvcRouteHandler(),
ServiceProvider = app.ApplicationServices
};
configureRoutes(routes);
// Adding the attribute route comes after running the user-code because
// we want to respect any changes to the DefaultHandler.
routes.Routes.Insert(0, AttributeRouting.CreateAttributeMegaRoute(
routes.DefaultHandler,
app.ApplicationServices));
return app.UseRouter(routes.Build());
}
The good thing about this is that the framework now handles all the hard work, iterating through all the Controller's Actions and setting up their default routes, thus saving you some redundant work.
The bad thing is, there's little or no documentation about how you could add your own routes. Luckily enough, you can easily do that by using either a Convention-Based and/or an Attribute-Based approach (aka Attribute Routing).
Convention-Based
In your Startup.cs class, replace this:
app.UseMvc();
with this:
app.UseMvc(routes =>
{
// Route Sample A
routes.MapRoute(
name: "RouteSampleA",
template: "MyOwnGet",
defaults: new { controller = "Items", action = "Get" }
);
// Route Sample B
routes.MapRoute(
name: "RouteSampleB",
template: "MyOwnPost",
defaults: new { controller = "Items", action = "Post" }
);
});
Attribute-Based
A great thing about MVC6 is that you can also define routes on a per-controller basis by decorating either the Controller
class and/or the Action
methods with the appropriate RouteAttribute
and/or HttpGet
/ HttpPost
template parameters, such as the following:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
namespace MyNamespace.Controllers
{
[Route("api/[controller]")]
public class ItemsController : Controller
{
// GET: api/items
[HttpGet()]
public IEnumerable<string> Get()
{
return GetLatestItems();
}
// GET: api/items/5
[HttpGet("{num}")]
public IEnumerable<string> Get(int num)
{
return GetLatestItems(5);
}
// GET: api/items/GetLatestItems
[HttpGet("GetLatestItems")]
public IEnumerable<string> GetLatestItems()
{
return GetLatestItems(5);
}
// GET api/items/GetLatestItems/5
[HttpGet("GetLatestItems/{num}")]
public IEnumerable<string> GetLatestItems(int num)
{
return new string[] { "test", "test2" };
}
// POST: /api/items/PostSomething
[HttpPost("PostSomething")]
public IActionResult Post([FromBody]string someData)
{
return Content("OK, got it!");
}
}
}
This controller will handle the following requests:
[GET] api/items
[GET] api/items/5
[GET] api/items/GetLatestItems
[GET] api/items/GetLatestItems/5
[POST] api/items/PostSomething
Also notice that if you use the two approaches togheter, Attribute-based routes (when defined) would override Convention-based ones, and both of them would override the default routes defined by UseMvc()
.
For more info, you can also read the following post on my blog.
below query gives you time of the date
select DateAdd(day,-DateDiff(day,0,YourDateTime),YourDateTime) As NewTime from Table
Below are the main actions which will avoid a lot of errors when using Google play service Lib:
PDFBox contains tools for text extraction.
iText has more low-level support for text manipulation, but you'd have to write a considerable amount of code to get text extraction.
iText in Action contains a good overview of the limitations of text extraction from PDF, regardless of the library used (Section 18.2: Extracting and editing text), and a convincing explanation why the library does not have text extraction support. In short, it's relatively easy to write a code that will handle simple cases, but it's basically impossible to extract text from PDF in general.
You need to use bitwise operators |
instead of or
and &
instead of and
in pandas, you can't simply use the bool statements from python.
For much complex filtering create a mask
and apply the mask on the dataframe.
Put all your query in the mask and apply it.
Suppose,
mask = (df["col1"]>=df["col2"]) & (stock["col1"]<=df["col2"])
df_new = df[mask]
It is an annotation to suppress compile warnings about unchecked generic operations (not exceptions), such as casts. It essentially implies that the programmer did not wish to be notified about these which he is already aware of when compiling a particular bit of code.
You can read more on this specific annotation here:
Additionally, Oracle provides some tutorial documentation on the usage of annotations here:
As they put it,
"The 'unchecked' warning can occur when interfacing with legacy code written before the advent of generics (discussed in the lesson titled Generics)."
If you're using 0
and an empty string ''
and null
to designate undefined you've got a data problem. Just update the columns and fix your schema.
UPDATE pt.incentive_channel
SET pt.incentive_marketing = NULL
WHERE pt.incentive_marketing = '';
UPDATE pt.incentive_channel
SET pt.incentive_advertising = NULL
WHERE pt.incentive_marketing = '';
UPDATE pt.incentive_channel
SET pt.incentive_channel = NULL
WHERE pt.incentive_marketing = '';
This will make joining and selecting substantially easier moving forward.
Try Libman, it's as simple as Bower and you can specify wwwroot/lib/ as the download folder.
I was searching for similar solution. The replies here and the Tutorial on top is informative. I studied posts/blogs referred here to build mine successful. I am posting complete CMakeLists.txt worked for me. I guess, this would be helpful as a basic template for beginners.
"CMakeLists.txt"
cmake_minimum_required(VERSION 3.10.2)
# Target Project
project (ClientProgram)
# Begin: Including Sources and Headers
include_directories(include)
file (GLOB SOURCES "src/*.c")
# End: Including Sources and Headers
# Begin: Generate executables
add_executable (ClientProgram ${SOURCES})
# End: Generate executables
# This Project Depends on External Project(s)
include (ExternalProject)
# Begin: External Third Party Library
set (libTLS ThirdPartyTlsLibrary)
ExternalProject_Add (${libTLS}
PREFIX ${CMAKE_CURRENT_BINARY_DIR}/${libTLS}
# Begin: Download Archive from Web Server
URL http://myproject.com/MyLibrary.tgz
URL_HASH SHA1=<expected_sha1sum_of_above_tgz_file>
DOWNLOAD_NO_PROGRESS ON
# End: Download Archive from Web Server
# Begin: Download Source from GIT Repository
# GIT_REPOSITORY https://github.com/<project>.git
# GIT_TAG <Refer github.com releases -> Tags>
# GIT_SHALLOW ON
# End: Download Source from GIT Repository
# Begin: CMAKE Comamnd Argiments
CMAKE_ARGS -DCMAKE_INSTALL_PREFIX:PATH=${CMAKE_CURRENT_BINARY_DIR}/${libTLS}
CMAKE_ARGS -DUSE_SHARED_LIBRARY:BOOL=ON
# End: CMAKE Comamnd Argiments
)
# The above ExternalProject_Add(...) construct wil take care of \
# 1. Downloading sources
# 2. Building Object files
# 3. Install under DCMAKE_INSTALL_PREFIX Directory
# Acquire Installation Directory of
ExternalProject_Get_Property (${libTLS} install_dir)
# Begin: Importing Headers & Library of Third Party built using ExternalProject_Add(...)
# Include PATH that has headers required by Target Project
include_directories (${install_dir}/include)
# Import librarues from External Project required by Target Project
add_library (lmytls SHARED IMPORTED)
set_target_properties (lmytls PROPERTIES IMPORTED_LOCATION ${install_dir}/lib/libmytls.so)
add_library (lmyxdot509 SHARED IMPORTED)
set_target_properties(lmyxdot509 PROPERTIES IMPORTED_LOCATION ${install_dir}/lib/libmyxdot509.so)
# End: Importing Headers & Library of Third Party built using ExternalProject_Add(...)
# End: External Third Party Library
# Begin: Target Project depends on Third Party Component
add_dependencies(ClientProgram ${libTLS})
# End: Target Project depends on Third Party Component
# Refer libraries added above used by Target Project
target_link_libraries (ClientProgram lmytls lmyxdot509)
Use DispatchGroup
s to achieve this. You can either get notified when the group's enter()
and leave()
calls are balanced:
func myFunction() {
var a: Int?
let group = DispatchGroup()
group.enter()
DispatchQueue.main.async {
a = 1
group.leave()
}
// does not wait. But the code in notify() gets run
// after enter() and leave() calls are balanced
group.notify(queue: .main) {
print(a)
}
}
or you can wait:
func myFunction() {
var a: Int?
let group = DispatchGroup()
group.enter()
// avoid deadlocks by not using .main queue here
DispatchQueue.global(attributes: .qosDefault).async {
a = 1
group.leave()
}
// wait ...
group.wait()
print(a) // you could also `return a` here
}
Note: group.wait()
blocks the current queue (probably the main queue in your case), so you have to dispatch.async
on another queue (like in the above sample code) to avoid a deadlock.
The way it works is to:
free (str3);
Here's an example for you play with. It's very simple and has no hard-coded lengths. You can try it here: http://ideone.com/d3g1xs
See this post for information about size of char
#include <stdio.h>
#include <memory.h>
int main(int argc, char** argv) {
char* str1;
char* str2;
str1 = "sssss";
str2 = "kkkk";
char * str3 = (char *) malloc(1 + strlen(str1)+ strlen(str2) );
strcpy(str3, str1);
strcat(str3, str2);
printf("%s", str3);
return 0;
}
It looks like the machine you're trying to run this on has only 256 MB memory.
Maybe the JVM tries to allocate a large, contiguous block of 64 MB memory. The 192 MB that you have free might be fragmented into smaller pieces, so that there is no contiguous block of 64 MB free to allocate.
Try starting your Java program with a smaller heap size, for example:
java -Xms16m ...
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 startDay 110526 non-null object
1 endDay 110526 non-null object
import pandas as pd
df['startDay'] = pd.to_datetime(df.startDay)
df['endDay'] = pd.to_datetime(df.endDay)
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 startDay 110526 non-null datetime64[ns]
1 endDay 110526 non-null datetime64[ns]
For Express v4+
install body-parser from the npm.
$ npm install body-parser
https://www.npmjs.org/package/body-parser#installation
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// parse application/json
app.use(bodyParser.json())
app.use(function (req, res, next) {
console.log(req.body) // populated!
next()
})
$string = trim(preg_replace('/\s+/','',$string));
Use alter session set current_schema = <username>
, in your case as an execute immediate.
See Oracle's documentation for further information.
In your case, that would probably boil down to (untested)
DECLARE
CURSOR client_cur IS
SELECT distinct username
from all_users
where length(username) = 3;
-- client cursor
CURSOR emails_cur IS
SELECT id, name
FROM org;
BEGIN
FOR client IN client_cur LOOP
-- ****
execute immediate
'alter session set current_schema = ' || client.username;
-- ****
FOR email_rec in client_cur LOOP
dbms_output.put_line(
'Org id is ' || email_rec.id ||
' org nam ' || email_rec.name);
END LOOP;
END LOOP;
END;
/
You can do it like this:
<input type="hidden" name="result" value="<?php foreach($postvalue as $value) echo $postvalue.","; ?>">
As Shafik already wrote you need to use the right format because scanf
gets you a char.
Don't hesitate to look here if u aren't sure about the usage: http://www.cplusplus.com/reference/cstdio/printf/
Hint: It's faster/nicer to write x=x+1
; the shorter way: x++;
Sorry for answering what's answered just wanted to give him the link - the site was really useful to me all the time dealing with C.
It looks like the class.phpmailer.php file is corrupt. I would download the latest version and try again.
I've always used phpMailer's SMTP feature:
$mail->IsSMTP();
$mail->Host = "localhost";
And if you need debug info:
$mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
// 1 = errors and messages
// 2 = messages only
Ok what you probably want will be provide to you by result of:
in CSS:
div { column-count: 2; }
in html:
<div> some text, bla bla bla </div>
In CSS you make div to split your paragraph on to column, you can make them 3, 4...
If you want to have many differend paragraf like that, then put id or class in your div:
Here is a basic example:
public class TestMethodPassing
{
private static void println()
{
System.out.println("Do println");
}
private static void print()
{
System.out.print("Do print");
}
private static void performTask(BasicFunctionalInterface functionalInterface)
{
functionalInterface.performTask();
}
@FunctionalInterface
interface BasicFunctionalInterface
{
void performTask();
}
public static void main(String[] arguments)
{
performTask(TestMethodPassing::println);
performTask(TestMethodPassing::print);
}
}
Output:
Do println
Do print
In my case, I created a new project and when I ran it the first time, it gave me the following error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
So my solution was to go to the Package Manager Console inside the Visual Studio and run:Update-Package
Problem solved!!
Attention: The other answers only work on SQL Servers with English configuration! Use SET DATEFIRST 7
to ensure DATEPART(DW, ...)
returns 1 for Sunday and 7 for Saturday.
Here's a version that is independent of the local setting and does not require to use :
CREATE FUNCTION [dbo].[fct_IsDateWeekend] ( @date DATETIME )
RETURNS BIT
AS
BEGIN
RETURN CASE WHEN DATEPART(DW, @date + @@DATEFIRST - 1) > 5 THEN 1 ELSE 0 END;
END;
If you don't want to use the function, simply use this in your SELECT statement:
CASE WHEN DATEPART(DW, YourDateTime + @@DATEFIRST - 1) > 5 THEN 'Weekend' ELSE 'Weekday' END
Beyond what's been said already about selectors, you may want to look at the NSInvocation class.
An NSInvocation is an Objective-C message rendered static, that is, it is an action turned into an object. NSInvocation objects are used to store and forward messages between objects and between applications, primarily by NSTimer objects and the distributed objects system.
An NSInvocation object contains all the elements of an Objective-C message: a target, a selector, arguments, and the return value. Each of these elements can be set directly, and the return value is set automatically when the NSInvocation object is dispatched.
Keep in mind that while it's useful in certain situations, you don't use NSInvocation in a normal day of coding. If you're just trying to get two objects to talk to each other, consider defining an informal or formal delegate protocol, or passing a selector and target object as has already been mentioned.
While it's rather old, this might be a handy solution for some:
A little module that extends the threading's module functionality -- allows one thread to raise exceptions in the context of another thread. By raising
SystemExit
, you can finally kill python threads.
import threading
import ctypes
def _async_raise(tid, excobj):
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(excobj))
if res == 0:
raise ValueError("nonexistent thread id")
elif res > 1:
# """if it returns a number greater than one, you're in trouble,
# and you should call it again with exc=NULL to revert the effect"""
ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0)
raise SystemError("PyThreadState_SetAsyncExc failed")
class Thread(threading.Thread):
def raise_exc(self, excobj):
assert self.isAlive(), "thread must be started"
for tid, tobj in threading._active.items():
if tobj is self:
_async_raise(tid, excobj)
return
# the thread was alive when we entered the loop, but was not found
# in the dict, hence it must have been already terminated. should we raise
# an exception here? silently ignore?
def terminate(self):
# must raise the SystemExit type, instead of a SystemExit() instance
# due to a bug in PyThreadState_SetAsyncExc
self.raise_exc(SystemExit)
So, it allows a "thread to raise exceptions in the context of another thread" and in this way, the terminated thread can handle the termination without regularly checking an abort flag.
However, according to its original source, there are some issues with this code.
- The exception will be raised only when executing python bytecode. If your thread calls a native/built-in blocking function, the exception will be raised only when execution returns to the python code.
- There is also an issue if the built-in function internally calls PyErr_Clear(), which would effectively cancel your pending exception. You can try to raise it again.
- Only exception types can be raised safely. Exception instances are likely to cause unexpected behavior, and are thus restricted.
- For example: t1.raise_exc(TypeError) and not t1.raise_exc(TypeError("blah")).
- IMHO it's a bug, and I reported it as one. For more info, http://mail.python.org/pipermail/python-dev/2006-August/068158.html
- I asked to expose this function in the built-in thread module, but since ctypes has become a standard library (as of 2.5), and this
feature is not likely to be implementation-agnostic, it may be kept
unexposed.
If you want to get current directory path within a file for that you can magic constants __FILE__
and __DIR__
with plugin_dir_path()
function as:
$dir_path = plugin_dir_path( __FILE__ );
CurrentDirectory Path:
/home/user/var/www/wordpress_site/wp-content/plugins/custom-plugin/
__FILE__
magic constant returns current directory path.
If you want to one level up from the current directory. You should use __DIR__
magic constant as:
Current Path:
/home/user/var/www/wordpress_site/wp-content/plugins/custom-plugin/
$dir = plugin_dir_path( __DIR__ );
One level up path:
/home/user/var/www/wordpress_site/wp-content/plugins/
__DIR__
magic constant returns one level up directory path.
You can try
grep -f file1 file2
or
grep -v -F -x -f file1 file2
var_dump
displays structured information about the object / variable. This includes type and values. Like print_r
arrays are recursed through and indented.
print_r
displays human readable information about the values with a format presenting keys and elements for arrays and objects.
The most important thing to notice is var_dump
will output type as well as values while print_r
does not.
For this, enter the command:
git pull origin branchname --allow-unrelated-histories
For example,
git pull origin master --allow-unrelated-histories
Reference:
Try this option:
radio1.Items.FindByValue("1").Selected = true;
Simplistic Shell code for creating WAR files from a standard Eclipse dynamic Web Project. Uses RAM File system (/dev/shm) on a Linux platform.
#!/bin/sh
UTILITY=$(basename $0)
if [ -z "$1" ] ; then
echo "usage: $UTILITY [-s] <web-app-directory>..."
echo " -s ..... With source"
exit 1
fi
if [ "$1" == "-s" ] ; then
WITH_SOURCE=1
shift
fi
while [ ! -z "$1" ] ; do
WEB_APP_DIR=$1
shift
if [ ! -d $WEB_APP_DIR ] ; then
echo "\"$WEB_APP_DIR\" is not a directory"
continue
fi
if [ ! -d $WEB_APP_DIR/WebContent ] ; then
echo "\"$WEB_APP_DIR\" is not a Web Application directory"
continue
fi
TMP_DIR=/dev/shm/${WEB_APP_DIR}.$$.tmp
WAR_FILE=/dev/shm/${WEB_APP_DIR}.war
mkdir $TMP_DIR
pushd $WEB_APP_DIR > /dev/null
cp -r WebContent/* $TMP_DIR
cp -r build/* $TMP_DIR/WEB-INF
[ ! -z "$WITH_SOURCE" ] && cp -r src/* $TMP_DIR/WEB-INF/classes
cd $TMP_DIR > /dev/null
[ -e $WAR_FILE ] && rm -f $WAR_FILE
jar cf $WAR_FILE .
ls -lsF $WAR_FILE
popd > /dev/null
rm -rf $TMP_DIR
done
This solution is even simpler than the one provided by Leigh
. It is actually based on it.
Here you can notice that the middle element (in our case, with "content__middle"
class) does not have any dimensional property specified - no width, nor padding, nor margin related property at all - but only an overflow: auto;
(see note 1).
The great advantage is that now you can specify a max-width
and a min-width
to your left & right elements. Which is fantastic for fluid layouts.. hence responsive layout :-)
note 1: versus Leigh's answer where you need to add the margin-left
& margin-right
properties to the "content__middle"
class.
Here the left & right elements (with classes "content__left"
and "content__right"
) have a fixed width (in pixels): hence called non-fluid layout.
Live Demo on http://jsbin.com/qukocefudusu/1/edit?html,css,output
<style>
/*
* [1] & [3] "floats" makes the 2 divs align themselves respectively right & left
* [2] "overflow: auto;" makes this div take the remaining width
*/
.content {
width: 100%;
}
.content__left {
width: 100px;
float: left; /* [1] */
background-color: #fcc;
}
.content__middle {
background-color: #cfc;
overflow: auto; /* [2] */
}
.content__right {
width: 100px;
float: right; /* [3] */
background-color: #ccf;
}
</style>
<div class="content">
<div class="content__left">
left div<br/>left div<br/>left div<br/>left div<br/>left div<br/>left div<br/>
</div>
<div class="content__right">
right div<br/>right div<br/>right div<br/>right div<br/>
</div>
<div class="content__middle">
middle div<br/>middle div<br/>middle div<br/>middle div<br/>middle div<br/>middle div<br/>middle div<br/>middle div<br/>middle div<br />bit taller
</div>
</div>
Here the left & right elements (with classes "content__left"
and "content__right"
) have a variable width (in percentages) but also a minimum and maximum width: hence called fluid layout.
Live Demo in a fluid layout with the max-width
properties http://jsbin.com/runahoremuwu/1/edit?html,css,output
<style>
/*
* [1] & [3] "floats" makes the 2 divs align themselves respectively right & left
* [2] "overflow: auto;" makes this div take the remaining width
*/
.content {
width: 100%;
}
.content__left {
width: 20%;
max-width: 170px;
min-width: 40px;
float: left; /* [1] */
background-color: #fcc;
}
.content__middle {
background-color: #cfc;
overflow: auto; /* [2] */
}
.content__right {
width: 20%;
max-width: 250px;
min-width: 80px;
float: right; /* [3] */
background-color: #ccf;
}
</style>
<div class="content">
<div class="content__left">
max-width of 170px & min-width of 40px<br />left div<br/>left div<br/>left div<br/>left div<br/>left div<br/>left div<br/>
</div>
<div class="content__right">
max-width of 250px & min-width of 80px<br />right div<br/>right div<br/>right div<br/>right div<br/>
</div>
<div class="content__middle">
middle div<br/>middle div<br/>middle div<br/>middle div<br/>middle div<br/>middle div<br/>middle div<br/>middle div<br/>middle div<br />bit taller
</div>
</div>
Tested on BrowserStack.com on the following web browsers:
There is a better algorithm, which needs at most 6 iterations to converge to maximum precision for double numbers:
#include <math.h>
double sqrt(double x) {
if (x <= 0)
return 0; // if negative number throw an exception?
int exp = 0;
x = frexp(x, &exp); // extract binary exponent from x
if (exp & 1) { // we want exponent to be even
exp--;
x *= 2;
}
double y = (1+x)/2; // first approximation
double z = 0;
while (y != z) { // yes, we CAN compare doubles here!
z = y;
y = (y + x/y) / 2;
}
return ldexp(y, exp/2); // multiply answer by 2^(exp/2)
}
Algorithm starts with 1 as first approximation for square root value.
Then, on each step, it improves next approximation by taking average between current value y
and x/y
. If y
= sqrt(x)
, it will be the same. If y
> sqrt(x)
, then x/y
< sqrt(x)
by about the same amount. In other words, it will converge very fast.
UPDATE: To speed up convergence on very large or very small numbers, changed sqrt()
function to extract binary exponent and compute square root from number in [1, 4)
range. It now needs frexp()
from <math.h>
to get binary exponent, but it is possible to get this exponent by extracting bits from IEEE-754 number format without using frexp()
.
If you have a group of radio button and you want to set radio button checked based on model, then radio button which has same value
and ng-model
, is checked automatically.
<input type="radio" value="1" ng-model="myRating" name="rating" class="radio">
<input type="radio" value="2" ng-model="myRating" name="rating" class="radio">
<input type="radio" value="3" ng-model="myRating" name="rating" class="radio">
<input type="radio" value="4" ng-model="myRating" name="rating" class="radio">
If the value of myRating
is "2" then second radio button is selected.
I just tried to call a function in terminal rather then MySQL Query Browser and it works. So, it looks like I'm doing something wrong in that program...
I don't know what since I called some procedures before successfully (but there where no out parameters)...
For this one I had entered
CALL my_sqrt(4,@out_value);
SELECT @out_value;
And it results with an error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT @out_value' at line 2
Strangely, if I write just:
CALL my_sqrt(4,@out_value);
The result message is: "Query canceled"
I guess, for now I will use only terminal...
The answer was to install the plugin individually. I installed all the three plugins shown in the screenshot together. And it created the issue. I had to install each plugin individually and then it worked fine. I am able to format the JSON string.
Your question is a bit vague about what you are actually thinking about doing. "Cloud computing" can mean almost anything. If you're looking for languages with specific cloud computing advantages, Java has several because it's a compiled language that compiles to operating-system independent byte code.
I also chime in with the others about C++ being a low-level language. Yes, it is. But you're always going to have more than just the C++ language. If you separate both Java and C++ from the classes that come with them, Java and C++ are extremely similar. You have to adopt some rigid criterion like "pointers = low-level, garbage collection = high-level" to make the distinction stick. (And, of course, you can make pointers smart and invisible in C++ and you can use garbage collection in C++ too if you want to.)
My solution was to create a disabled class in CSS:
.disabled {
pointer-events: none;
cursor: not-allowed;
}
and then your select would be:
<select name="sel" class="disabled">
<option>123</option>
</select>
The user would be unable to pick any values but the select value would still be passed on form submission.
I think there is a semantic problem here. In my view, a user can have a (but only one) favourite recipe to prepare a specific menu. (The OP has menu and recipe mixed up; if I am wrong: please interchange MenuId and RecipeId below) That implies that {user,menu} should be a unique key in this table. And it should point to exactly one recipe. If the user has no favourite recipe for this specific menu no row should exist for this {user,menu} key pair. Also: the surrogate key (FaVouRiteId) is superfluous: composite primary keys are perfectly valid for relational-mapping tables.
That would lead to the reduced table definition:
CREATE TABLE Favorites
( UserId uuid NOT NULL REFERENCES users(id)
, MenuId uuid NOT NULL REFERENCES menus(id)
, RecipeId uuid NOT NULL REFERENCES recipes(id)
, PRIMARY KEY (UserId, MenuId)
);
2 workarounds, rather than a solution: In my Git Bash, following command hangs and I don't get the prompt back:
% python
So I just use:
% winpty python
As some people have noted above, you can also use:
% python -i
2020-07-14: Git 2.27.0 has added optional experimental support for pseudo consoles, which allow running Python from the command line:
putExtra() : This method sends the data to another activity and in parameter, we have to pass key-value pair.
Syntax: intent.putExtra("key", value);
Eg: intent.putExtra("full_name", "Vishnu Sivan");
Intent intent=getIntent()
: It gets the Intent from the previous activity.
fullname = intent.getStringExtra(“full_name”)
: This line gets the string form previous activity and in parameter, we have to pass the key which we have mentioned in previous activity.
Sample Code:
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("firstName", "Vishnu");
intent.putExtra("lastName", "Sivan");
startActivity(intent);
Tag ids must be unique. You are updating the span with ID 'ItemCostSpan' of which there are two. Give the span a class and get it using find.
$("legend").each(function() {
var SoftwareItem = $(this).text();
itemCost = GetItemCost(SoftwareItem);
$("input:checked").each(function() {
var Component = $(this).next("label").text();
itemCost += GetItemCost(Component);
});
$(this).find(".ItemCostSpan").text("Item Cost = $ " + itemCost);
});
I like this naming style:
OrdersShouldBeCreated();
OrdersWithNoProductsShouldFail();
and so on. It makes really clear to a non-tester what the problem is.
Attribute is a public variable inside the class/object. length attribute is a variable of int type.
foo4
is initialised by default-constructing, copying and destroying a temporary object; usually, this is elided giving the same result as 3.Foo foo5
is a declaration, not an expression; function (and constructor) arguments must be expressions.Foo()
rather than the equivalent Foo::Foo()
(or indeed Foo::Foo::Foo::Foo::Foo()
)When do I use each?
Bar
from a temporary Foo
.One liner for Python based on scai's answer, but a) takes stdin, b) makes the result repeatable with seed, c) picks out only 200 of all lines.
$ cat file | python -c "import random, sys;
random.seed(100); print ''.join(random.sample(sys.stdin.readlines(), 200))," \
> 200lines.txt
On Window machine install any version of Git. I installed
Git-2.14.1-64-bit.exe
. Got to search program and search for git.exe. The file can be located under
C:\Users\sd\AppData\Local\Programs\Git\bin\git.exe
.
Open Intelli IDEA>Settings>Version Control>Git. On Path To Git executable add the path. Click on Test button. It will show a message as
Git executed successfully
Now click on Apply and Save. This will solve the issue. .
You can delete the archive files and executable binaries that go install
(or go get
) produces for a package with go clean -i importpath...
. These normally reside under $GOPATH/pkg
and $GOPATH/bin
, respectively.
Be sure to include ...
on the importpath, since it appears that, if a package includes an executable, go clean -i
will only remove that and not archive files for subpackages, like gore/gocode
in the example below.
Source code then needs to be removed manually from $GOPATH/src
.
go clean
has an -n
flag for a dry run that prints what will be run without executing it, so you can be certain (see go help clean
). It also has a tempting -r
flag to recursively clean dependencies, which you probably don't want to actually use since you'll see from a dry run that it will delete lots of standard library archive files!
A complete example, which you could base a script on if you like:
$ go get -u github.com/motemen/gore
$ which gore
/Users/ches/src/go/bin/gore
$ go clean -i -n github.com/motemen/gore...
cd /Users/ches/src/go/src/github.com/motemen/gore
rm -f gore gore.exe gore.test gore.test.exe commands commands.exe commands_test commands_test.exe complete complete.exe complete_test complete_test.exe debug debug.exe helpers_test helpers_test.exe liner liner.exe log log.exe main main.exe node node.exe node_test node_test.exe quickfix quickfix.exe session_test session_test.exe terminal_unix terminal_unix.exe terminal_windows terminal_windows.exe utils utils.exe
rm -f /Users/ches/src/go/bin/gore
cd /Users/ches/src/go/src/github.com/motemen/gore/gocode
rm -f gocode.test gocode.test.exe
rm -f /Users/ches/src/go/pkg/darwin_amd64/github.com/motemen/gore/gocode.a
$ go clean -i github.com/motemen/gore...
$ which gore
$ tree $GOPATH/pkg/darwin_amd64/github.com/motemen/gore
/Users/ches/src/go/pkg/darwin_amd64/github.com/motemen/gore
0 directories, 0 files
# If that empty directory really bugs you...
$ rmdir $GOPATH/pkg/darwin_amd64/github.com/motemen/gore
$ rm -rf $GOPATH/src/github.com/motemen/gore
Note that this information is based on the go
tool in Go version 1.5.1.
If you just want to select elements that contain given string then you can use following selector:
$(':contains("search string")')
you have a few options here:
I personally use the Used Range and find last row and column method most of the time.
Here's how you would do it using the UsedRange property:
Sheets("Sheet_Name").UsedRange.Select
This statement will select all used ranges in the worksheet, note that sometimes this doesn't work very well when you delete columns and rows.
The alternative is to find the very last cell used in the worksheet
Dim rngTemp As Range
Set rngTemp = Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious)
If Not rngTemp Is Nothing Then
Range(Cells(1, 1), rngTemp).Select
End If
What this code is doing:
A copy-paste solution (extension methods) mostly based on earlier responses to this question.
Also properly handles IDicitonary (ExpandoObject/dynamic) which is often needed when dealing with this reflected stuff.
Not recommended for use in tight loops and other hot paths. In those cases you're gonna need some caching/IL emit/expression tree compilation.
public static IEnumerable<(string Name, object Value)> GetProperties(this object src)
{
if (src is IDictionary<string, object> dictionary)
{
return dictionary.Select(x => (x.Key, x.Value));
}
return src.GetObjectProperties().Select(x => (x.Name, x.GetValue(src)));
}
public static IEnumerable<PropertyInfo> GetObjectProperties(this object src)
{
return src.GetType()
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(p => !p.GetGetMethod().GetParameters().Any());
}
Two of the most common
First way :
let jsonData = require('./JsonFile.json')
let jsonData = require('./JsonFile')
// if we omitting .json also works
OR
import jsonData from ('./JsonFile.json')
Second way :
1) synchronously
const fs = require('fs')
let jsonData = JSON.parse(fs.readFileSync('JsonFile.json', 'utf-8'))
2) asynchronously
const fs = require('fs')
let jsonData = {}
fs.readFile('JsonFile.json', 'utf-8', (err, data) => {
if (err) throw err
jsonData = JSON.parse(data)
})
Note: 1) if we JsonFile.json is changed, we not get the new data, even if we re run require('./JsonFile.json')
2) The fs.readFile or fs.readFileSync will always re read the file, and get changes
Just wrote before for the same reason (works with any amount of arrays):
/**
* Returns with the union of the given arrays.
*
* @param Any amount of arrays to be united.
* @returns {array} The union array.
*/
function uniteArrays()
{
var union = [];
for (var argumentIndex = 0; argumentIndex < arguments.length; argumentIndex++)
{
eachArgument = arguments[argumentIndex];
if (typeof eachArgument !== 'array')
{
eachArray = eachArgument;
for (var index = 0; index < eachArray.length; index++)
{
eachValue = eachArray[index];
if (arrayHasValue(union, eachValue) == false)
union.push(eachValue);
}
}
}
return union;
}
function arrayHasValue(array, value)
{ return array.indexOf(value) != -1; }
Change SUM(billableDuration) AS NumSecondsDelivered
to
sum(cast(billableDuration as bigint))
or
sum(cast(billableDuration as numeric(12, 0)))
according to your need.
The resultant type of of Sum expression is the same as the data type used. It throws error at time of overflow. So casting the column to larger capacity data type and then using Sum operation works fine.
The ALTER TABLE
MySQL command should do the trick. The following command will change the default character set of your table and the character set of all its columns to UTF8.
ALTER TABLE etape_prospection CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;
This command will convert all text-like columns in the table to the new character set. Character sets use different amounts of data per character, so MySQL will convert the type of some columns to ensure there's enough room to fit the same number of characters as the old column type.
I recommend you read the ALTER TABLE MySQL documentation before modifying any live data.
If you have problems uninstalling through adb, I can recommend the following tool:
https://github.com/patrickfav/uber-adb-tools
you can use wildcards and supports multiple devices, also has some better error handling than the vanilla ADB (but uses it in background of course). Will work on your platform.
Full disclaimer: I am the developer
<?php
// Checks if key exists (doesn't care about it's value).
// @link http://php.net/manual/en/function.array-key-exists.php
if (array_key_exists(20120504, $search_array)) {
echo $search_array[20120504];
}
// Checks against NULL
// @link http://php.net/manual/en/function.isset.php
if (isset($search_array[20120504])) {
echo $search_array[20120504];
}
// No warning or error if key doesn't exist plus checks for emptiness.
// @link http://php.net/manual/en/function.empty.php
if (!empty($search_array[20120504])) {
echo $search_array[20120504];
}
?>
I will make a little bit wider answer here.
There are generally speaking two types of conditional jumps in x86:
Arithmetic jumps - like JZ (jump if zero), JC (jump if carry), JNC (jump if not carry), etc.
Comparison jumps - JE (jump if equal), JB (jump if below), JAE (jump if above or equal), etc.
So, use the first type only after arithmetic or logical instructions:
sub eax, ebx
jnz .result_is_not_zero
and ecx, edx
jz .the_bit_is_not_set
Use the second group only after CMP instructions:
cmp eax, ebx
jne .eax_is_not_equal_to_ebx
cmp ecx, edx
ja .ecx_is_above_than_edx
This way, the program becomes more readable and you will never be confused.
Note, that sometimes these instructions are actually synonyms. JZ == JE; JC == JB; JNC == JAE and so on. The full table is following. As you can see, there are only 16 conditional jump instructions, but 30 mnemonics - they are provided to allow creation of more readable source code:
Mnemonic Condition tested Description
jo OF = 1 overflow
jno OF = 0 not overflow
jc, jb, jnae CF = 1 carry / below / not above nor equal
jnc, jae, jnb CF = 0 not carry / above or equal / not below
je, jz ZF = 1 equal / zero
jne, jnz ZF = 0 not equal / not zero
jbe, jna CF or ZF = 1 below or equal / not above
ja, jnbe CF and ZF = 0 above / not below or equal
js SF = 1 sign
jns SF = 0 not sign
jp, jpe PF = 1 parity / parity even
jnp, jpo PF = 0 not parity / parity odd
jl, jnge SF xor OF = 1 less / not greater nor equal
jge, jnl SF xor OF = 0 greater or equal / not less
jle, jng (SF xor OF) or ZF = 1 less or equal / not greater
jg, jnle (SF xor OF) or ZF = 0 greater / not less nor equal
Is there something that prevents you from merging all revisions on trunk since the last merge?
svn merge -rLastRevisionMergedFromTrunkToBranch:HEAD url/of/trunk path/to/branch/wc
should work just fine. At least if you want to merge all changes on trunk to your branch.
If you use bower.json file to specify your dependencies:
{
"dependencies": {
...
"photo-swipe": "[email protected]:dimsemenov/PhotoSwipe.git#v3.0.x",
#bower 1.4 (tested with that version) can read repositorios with uri format
"photo-swipe": "git://github.com/dimsemenov/PhotoSwipe.git#v3.0.x",
}
}
Just remember bower also searches for released versions and tags so you can point to almost everything, and can interprate basic query patterns like previous example. that will fetch latest minor update of version 3.0 (tested from bower 1.3.5)
Update, as the question description also mention using only a URL and no mention of a github repository.
Another example is to execute this command using the desired url, like:
bower install gmap3MarkerWithLabel=http://google-maps-utility-library-v3.googlecode.com/svn/tags/markerwithlabel/1.0/src/markerwithlabel.js -S
that command downloads your js library puts in {your destination path}/gmap3MarkerWithLabel/index.js and automatically creates an entry in your bower.json file called gmap3MarkerWithLabel: "..." After that, you can only execute bower update gmap3MarkerWithLabel
if needed.
Funny thing if you do the process backwars (add manually the entry in bower.json, an then bower install entryName) it doesn't work, you get a
bower ENOTFOUND Package gmapV3MarkerWithLabel not found
In Java 8 and later, use the java.time framework (Tutorial).
Duration
The Duration
class represents a span of time as a number of seconds plus a fractional second. It can count days, hours, minutes, and seconds.
ZonedDateTime now = ZonedDateTime.now();
ZonedDateTime oldDate = now.minusDays(1).minusMinutes(10);
Duration duration = Duration.between(oldDate, now);
System.out.println(duration.toDays());
ChronoUnit
If all you need is the number of days, alternatively you can use the ChronoUnit
enum. Notice the calculation methods return a long
rather than int
.
long days = ChronoUnit.DAYS.between( then, now );
Do a force Maven Update which will bring the compatible 1.8 Jar Versions and then while building, update the JRE Versions in Execute environment to 1.8 from Run Configurations and hit RUN
Note the ""
at the beginning and at the end!
Run a program and pass a Long Filename
cmd /c write.exe "c:\sample documents\sample.txt"
Spaces in Program Path
cmd /c ""c:\Program Files\Microsoft Office\Office\Winword.exe""
Spaces in Program Path + parameters
cmd /c ""c:\Program Files\demo.cmd"" Parameter1 Param2
Spaces in Program Path + parameters with spaces
cmd /k ""c:\batch files\demo.cmd" "Parameter 1 with space" "Parameter2 with space""
Launch Demo1 and then Launch Demo2
cmd /c ""c:\Program Files\demo1.cmd" & "c:\Program Files\demo2.cmd""
#include <math.h>
printf ("%d", (int) pow (3, 4));
Try this:
select * from T_PARTNER
where C_DISTRIBUTOR_TYPE_ID = 6 and
translate(C_PARTNER_ID, '.1234567890', '.') is null;
From the description and from the reference to the search box in the Ubuntu site, I gather that you actually want an arrowhead character pointing to the right. There are no Unicode characters designed to be used as arrowheads, but some of them may visually resemble an arrowhead.
In particular, if you draw your idea of the character at Shapecatcher.com, you will find many suggestions, such as “>” RIGHT-POINTING ANGLE BRACKET' (U+232A) and “?” MEDIUM RIGHT-POINTING ANGLE BRACKET ORNAMENT (U+276D).
Such characters generally have limited support in fonts, so you would need to carefully write a longish font-family
list or to use a downloadable font. See my Guide to using special characters in HTML.
Especially if the intended use is as a symbol in a search box, as the reference to the Ubuntu page suggests, it is questionable whether you should use a character at all. It’s not really an element of text here; rather, a graphic symbol that accompanies text but isn’t a part of it. So why take all the trouble with using a character (safely), when it isn’t really a character?
Just add an ID tag to the input element... ie:
and check the value of the element in you javascript:
document.getElementById("question").value
Oh ya, get get firefox/firebug. It's the only way to do javascript.
I used tmux-powerline to fully pimp my tmux status bar. I was googling for a way to change to background of the status bar when your typing a tmux command. When I stumbled on this post I thought I should mention it for completeness.
Update: This project is in a maintenance mode and no future functionality is likely to be added. tmux-powerline, with all other powerline projects, is replaced by the new unifying powerline. However this project is still functional and can serve as a lightweight alternative for non-python users.
Here http://www.alteridem.net/2007/08/22/the-yield-statement-in-c/ is very good example:
public static IEnumerable<int> Range( int min, int max ) { while ( true ) { if ( min >= max ) { yield break; } yield return min++; } }
and explanation, that if a yield break
statement is hit within a method, execution of that method stops with no return. There are some time situations, when you don't want to give any result, then you can use yield break.
If you want to undo all files that was applied assume unchanged with any status, not only cached (git marks them by character in lower case), you can use the following command:
git ls-files -v | grep '^[a-z]' | cut -c 3- | tr '\012' '\000' | xargs -0 git update-index --no-assume-unchanged
git ls-files -v
will print all files with their statusgrep '^[a-z]'
will filter files and select only assume unchangedcut -c 3-
will remove status and leave only paths, cutting from the 3-rd character to the endtr '\012' '\000'
will replace end of line character (\012) to zero character (\000)xargs -0 git update-index --no-assume-unchanged
will pass all paths separated by zero character to git update-index --no-assume-unchanged
to undoimport re
s = raw_input('Type a word: ')
slower=''.join(re.findall(r'[a-z]',s))
supper=''.join(re.findall(r'[A-Z]',s))
print slower, supper
Prints:
Type a word: A Title of a Book
itleofaook ATB
Or you can use a list comprehension / generator expression:
slower=''.join(c for c in s if c.islower())
supper=''.join(c for c in s if c.isupper())
print slower, supper
Prints:
Type a word: A Title of a Book
itleofaook ATB
To test your browser, go to http://html5test.com/. The code is being maintained at: github dot com slash NielsLeenheer slash html5test.
I usualy use <li>
to include <a>
link. I disabled click action writing like this;
You may not include <a>
link, then you will ignore my post.
a.noclick {_x000D_
pointer-events: none;_x000D_
}
_x000D_
<a class="noclick" href="#">this is disabled</a>
_x000D_
I had the same problem. Check wether plt.isinteractive()
is True. Setting it to 'False' helped for me.
plt.interactive(False)
cascade = { CascadeType.ALL }, fetch = FetchType.LAZY
I have learned it is also possible to do this with the exec-maven-plugin if you're doing a "standalone" java app.
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>${maven.exec.plugin.version}</version>
<executions>
<execution>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>
<configuration>
<mainClass>${exec.main-class}</mainClass>
<systemProperties>
<systemProperty>
<key>myproperty</key>
<value>myvalue</value>
</systemProperty>
</systemProperties>
</configuration>
</plugin>
android:minSdkVersion
and android:targetSdkVersion
both are Integer value we need to declare in android manifest file but both are having different properties.
android:minSdkVersion:
This is minimum required API level to run an android app. If we will install the same app on lower API version the parser error will be appear, and application not support problem will appear.
android:targetSdkVersion:
Target sdk version is to set the Target API level of app. if this attribute not declared in manifest, minSdk version will be your TargetSdk Version. This is always true that "app support installation on all higher version of API we declared as TargetSdk Version". To make app limited target we need to declare maxSdkVersion in our manifest file...
Assuming that your assembly/exe has FileIO permission is itself, well is not right. Your application may not run with admin rights. Its important to consider Code Access Security and requesting permissions Sample code:
FileIOPermission f2 = new FileIOPermission(FileIOPermissionAccess.Read, "C:\\test_r");
f2.AddPathList(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, "C:\\example\\out.txt");
try
{
f2.Demand();
}
catch (SecurityException s)
{
Console.WriteLine(s.Message);
}
Well, you can't. Internal classes can't be visible outside of their assembly, so no explicit way to access it directly -AFAIK of course. The only way is to use runtime late-binding via reflection, then you can invoke methods and properties from the internal class indirectly.
Try changing it to.
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "text/plain";
Response.Flush();
Response.TransmitFile(file.FullName);
Response.End();
Well, I used to do this way:
Imagine, you have 500 commits, and your erroneous commit message is in r.498.
hg qimport -r 498:tip
hg qpop -a
joe .hg/patches/498.diff
(change the comment, after the mercurial header)
hg qpush -a
hg qdelete -r qbase:qtip
Using Backtick
Backticks are commonly used for multi-line strings or when you want to interpolate an expression within your string
let title = 'John';_x000D_
let address = 'address';_x000D_
let address2 = 'address2222';_x000D_
let address3 = 'address33333';_x000D_
let address4 = 'address44444';_x000D_
document.getElementById("address_box").innerText = `${title} _x000D_
${address}_x000D_
${address2}_x000D_
${address3} _x000D_
${address4}`;
_x000D_
<div id="address_box">_x000D_
</div>
_x000D_
try this command in terminal:
sudo ufw enable
ufw allow 12397
Another way If you want to remove one or more than one character from the end.
var myStr = "Hello World!"
myStr = (myStr as NSString).substringToIndex((myStr as NSString).length-XX)
Where XX is the number of characters you want to remove.
The getting and setting of variables within classes refers to either retrieving ("getting") or altering ("setting") their contents.
Consider a variable members
of a class family
. Naturally, this variable would need to be an integer, since a family can never consist of two point something people.
So you would probably go ahead by defining the members
variable like this:
class family {
var members:Int
}
This, however, will give people using this class the possibility to set the number of family members to something like 0 or 1. And since there is no such thing as a family of 1 or 0, this is quite unfortunate.
This is where the getters and setters come in. This way you can decide for yourself how variables can be altered and what values they can receive, as well as deciding what content they return.
Returning to our family class, let's make sure nobody can set the members
value to anything less than 2:
class family {
var _members:Int = 2
var members:Int {
get {
return _members
}
set (newVal) {
if newVal >= 2 {
_members = newVal
} else {
println('error: cannot have family with less than 2 members')
}
}
}
}
Now we can access the members
variable as before, by typing instanceOfFamily.members
, and thanks to the setter function, we can also set it's value as before, by typing, for example: instanceOfFamily.members = 3
. What has changed, however, is the fact that we cannot set this variable to anything smaller than 2 anymore.
Note the introduction of the _members
variable, which is the actual variable to store the value that we set through the members
setter function. The original members
has now become a computed property, meaning that it only acts as an interface to deal with our actual variable.
Joe Edel's answer to himself is actually the right approach to resolve the pivot problem.
Basically the idea is to list out the columns in the base table firstly, and then any number of options.value
from the joint option table. Just left join
the same option table multiple times in order to get all the options.
What needs to be done by the programming language is to build this query dynamically according to a list of options needs to be queried.
If you are using Bootstrap version < 3...
With sass/scss
$baseBorderRadius: 0;
With less
@baseBorderRadius: 0;
You will need to set this variable before importing the bootstrap. This will affect all wells and navbars.
Update
If you are using Bootstrap 3 baseBorderRadius should be border-radius-base
In addition to the orbeckst answer one might also want to shift the subplots down. Here's an MWE in OOP style:
import matplotlib.pyplot as plt
fig = plt.figure()
st = fig.suptitle("suptitle", fontsize="x-large")
ax1 = fig.add_subplot(311)
ax1.plot([1,2,3])
ax1.set_title("ax1")
ax2 = fig.add_subplot(312)
ax2.plot([1,2,3])
ax2.set_title("ax2")
ax3 = fig.add_subplot(313)
ax3.plot([1,2,3])
ax3.set_title("ax3")
fig.tight_layout()
# shift subplots down:
st.set_y(0.95)
fig.subplots_adjust(top=0.85)
fig.savefig("test.png")
gives:
If you want to use dynamic variables
This won't work:
{{#each obj[key]}}
...
{{/each}}
You need to do:
{{#each (lookup obj key)}}
...
{{/each}}
Simple and easy :
<form onSubmit="return confirm('Do you want to submit?') ">_x000D_
<input type="submit" />_x000D_
</form>
_x000D_
Why do people use constants in classes instead of a variable?
readability and maintainability,
having some number like 40.023 in your code doesn't say much about what the number represents, so we replace it by a word in capitals like "USER_AGE_YEARS". Later when we look at the code its clear what that number represents.
Why do we not just use a variable? Well we would if we knew the number would change, but if its some number that wont change, like 3.14159.. we make it final.
But what if its not a number like a String? In that case its mostly for maintainability, if you are using a String multiple times in your code, (and it wont be changing at runtime) it is convenient to have it as a final string at the top of the class. That way when you want to change it, there is only one place to change it rather than many.
For example if you have an error message that get printed many times in your code, having final String ERROR_MESSAGE = "Something went bad." is easier to maintain, if you want to change it from "Something went bad." to "It's too late jim he's already dead", you would only need to change that one line, rather than all the places you would use that comment.
I had a different issue while creating a new app called deals
. I wanted to separate the models inside that app so I had 2 model files named deals.py
and dealers.py
.
When running python manage.py makemigrations
I got: No changes detected
.
I went ahead and inside the __init__.py
which lives on the same directory where my model files lived (deals and dealer) I did
from .deals import *
from .dealers import *
And then the makemigrations
command worked.
Turns out that if you are not importing the models anywhere OR your models file name isn't models.py
then the models wont be detected.
Another issue that happened to me is the way I wrote the app in settings.py
:
I had:
apps.deals
It should've been including the root project folder:
cars.apps.deals
There is an issue with iOS not registering click/touch events bound to elements added after DOM loads.
While PPK has this advice: http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
I've found this the easy fix, simply add this to the css:
cursor: pointer;
One line reduce
with ES6 fancy spread syntax is here!
var options = [_x000D_
{ name: 'One', assigned: true }, _x000D_
{ name: 'Two', assigned: false }, _x000D_
{ name: 'Three', assigned: true }, _x000D_
];_x000D_
_x000D_
const filtered = options_x000D_
.reduce((result, {name, assigned}) => [...result, ...assigned ? [name] : []], []);_x000D_
_x000D_
console.log(filtered);
_x000D_
it is a little different in xcode 7.3.1. this is what i come up with
// creating the view
let newView = UIView()
newView.backgroundColor = UIColor.redColor()
newView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(newView)
// creating the constraint
// attribute and relation cannot be set directyl you need to create a cariable of them
let layout11 = NSLayoutAttribute.CenterX
let layout21 = NSLayoutRelation.Equal
let layout31 = NSLayoutAttribute.CenterY
let layout41 = NSLayoutAttribute.Width
let layout51 = NSLayoutAttribute.Height
let layout61 = NSLayoutAttribute.NotAnAttribute
// defining all the constraint
let horizontalConstraint = NSLayoutConstraint(item: newView, attribute: layout11, relatedBy: layout21, toItem: view, attribute: layout11, multiplier: 1, constant: 0)
let verticalConstraint = NSLayoutConstraint(item: newView, attribute: layout31, relatedBy: layout21, toItem: view, attribute: layout31, multiplier: 1, constant: 0)
let widthConstraint = NSLayoutConstraint(item: newView, attribute: layout41, relatedBy: layout21, toItem: nil, attribute: layout61, multiplier: 1, constant: 100)
let heightConstraint = NSLayoutConstraint(item: newView, attribute: layout51, relatedBy: layout21, toItem: nil, attribute: layout61, multiplier: 1, constant: 100)
// adding all the constraint
NSLayoutConstraint.activateConstraints([horizontalConstraint,verticalConstraint,widthConstraint,heightConstraint])
replace:true
is DeprecatedFrom the Docs:
replace
([DEPRECATED!], will be removed in next major release - i.e. v2.0)specify what the template should replace. Defaults to
false
.
true
- the template will replace the directive's element.false
- the template will replace the contents of the directive's element.
-- AngularJS Comprehensive Directive API
From GitHub:
Caitp-- It's deprecated because there are known, very silly problems with
replace: true
, a number of which can't really be fixed in a reasonable fashion. If you're careful and avoid these problems, then more power to you, but for the benefit of new users, it's easier to just tell them "this will give you a headache, don't do it".
Note:
replace: true
is deprecated and not recommended to use, mainly due to the issues listed here. It has been completely removed in the new Angular.
transclude: element
in the replace template root can have unexpected effectsFor more information, see
Although this does not directly address your question, you can actually sort your data by cell colour in Excel (which then makes it pretty easy to label all records with a particular colour in the same way and, hence, condition upon this label).
In Excel 2010, you can do this by going to Data -> Sort -> Sort On "Cell Colour".
To remove entire row from DataTable , do like this
DataTable dt = new DataTable(); //User DataTable
DataRow[] rows;
rows = dt.Select("UserName = 'KarthiK'"); //'UserName' is ColumnName
foreach (DataRow row in rows)
dt.Rows.Remove(row);
If what you need is to count a specific file type recursively, you can do:
find YOUR_PATH -name '*.html' -type f | wc -l
-l
is just to display the number of lines in the output.
If you need to exclude certain folders, use -not -path
find . -not -path './node_modules/*' -name '*.js' -type f | wc -l
You might want to give XStream a shot, it is not complicated. It basically does the heavy lifting.
Using query comprehension syntax you could achieve the orderby as follows:
var uniqueColors = (from dbo in database.MainTable
where dbo.Property
orderby dbo.Color.Name ascending
select dbo.Color.Name).Distinct();
I found this way to do it in a very fast and easy way
<ComboBox x:Name="comboBox1" SelectedIndex="0" HorizontalAlignment="Left" Margin="202,43,0,0" VerticalAlignment="Top" Width="149">
<ComboBoxItem Visibility="Collapsed">
<TextBlock Foreground="Gray" FontStyle="Italic">Please select ...</TextBlock>
</ComboBoxItem>
<ComboBoxItem Name="cbiFirst1">First Item</ComboBoxItem>
<ComboBoxItem Name="cbiSecond1">Second Item</ComboBoxItem>
<ComboBoxItem Name="cbiThird1">third Item</ComboBoxItem>
</ComboBox>
Maybe it can help to anyone trying to do this
Source: http://www.admindiaries.com/displaying-a-please-select-watermark-type-text-in-a-wpf-combobox/
nginx "fails fast" when the client informs it that it's going to send a body larger than the client_max_body_size
by sending a 413 response and closing the connection.
Most clients don't read responses until the entire request body is sent. Because nginx closes the connection, the client sends data to the closed socket, causing a TCP RST.
If your HTTP client supports it, the best way to handle this is to send an Expect: 100-Continue
header. Nginx supports this correctly as of 1.2.7, and will reply with a 413 Request Entity Too Large
response rather than 100 Continue
if Content-Length
exceeds the maximum body size.
json.dumps()
is much more than just making a string out of a Python object, it would always produce a valid JSON string (assuming everything inside the object is serializable) following the Type Conversion Table.
For instance, if one of the values is None
, the str()
would produce an invalid JSON which cannot be loaded:
>>> data = {'jsonKey': None}
>>> str(data)
"{'jsonKey': None}"
>>> json.loads(str(data))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 382, in raw_decode
obj, end = self.scan_once(s, idx)
ValueError: Expecting property name: line 1 column 2 (char 1)
But the dumps()
would convert None
into null
making a valid JSON string that can be loaded:
>>> import json
>>> data = {'jsonKey': None}
>>> json.dumps(data)
'{"jsonKey": null}'
>>> json.loads(json.dumps(data))
{u'jsonKey': None}
jQuery ui 1.9 is going to take care of this for you. Heres a demo of the pre:
https://dl.dropbox.com/u/3872624/lab/touch/index.html
Just grab the jquery.mouse.ui.js out, stick it under the jQuery ui file you're loading, and that's all you should have to do! Works for sortable as well.
This code is working great for me, but if your getting errors, an updated version of jquery.mouse.ui.js can be found here:
Jquery-ui sortable doesn't work on touch devices based on Android or IOS
php artisan migrate --path=database/migrations/2020_04_10_130703_create_test_table.php
note: after --path no / before
In the Oracle RDBMS, it is possible to use a multi-row subquery in the select clause as long as the (sub-)output is encapsulated as a collection. In particular, a multi-row select clause subquery can output each of its rows as an xmlelement that is encapsulated in an xmlforest.
<input placeholder="Date" type="text" onMouseOver="(this.type='date')" onMouseOut="(this.type='text')" id="date" class="form-control">
_x000D_
Revised code of mumthezir
// this class will authenticate LDAP UserName or Email
// simply call LdapAuth.authenticateUserAndGetInfo (username,password);
//Note: Configure ldapURI ,requiredAttributes ,ADSearchPaths,accountSuffex
import java.util.*;
import javax.naming.*;
import java.util.regex.*;
import javax.naming.directory.*;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
public class LdapAuth {
private final static String ldapURI = "ldap://20.200.200.200:389/DC=corp,DC=local";
private final static String contextFactory = "com.sun.jndi.ldap.LdapCtxFactory";
private static String[] requiredAttributes = {"cn","givenName","sn","displayName","userPrincipalName","sAMAccountName","objectSid","userAccountControl"};
// see you active directory user OU's hirarchy
private static String[] ADSearchPaths =
{
"OU=O365 Synced Accounts,OU=ALL USERS",
"OU=Users,OU=O365 Synced Accounts,OU=ALL USERS",
"OU=In-House,OU=Users,OU=O365 Synced Accounts,OU=ALL USERS",
"OU=Torbram Users,OU=Users,OU=O365 Synced Accounts,OU=ALL USERS",
"OU=Migrated Users,OU=TES-Users"
};
private static String accountSuffex = "@corp.local"; // this will be used if user name is just provided
private static void authenticateUserAndGetInfo (String user, String password) throws Exception {
try {
Hashtable<String,String> env = new Hashtable <String,String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactory);
env.put(Context.PROVIDER_URL, ldapURI);
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, user);
env.put(Context.SECURITY_CREDENTIALS, password);
DirContext ctx = new InitialDirContext(env);
String filter = "(sAMAccountName="+user+")"; // default for search filter username
if(user.contains("@")) // if user name is a email then
{
//String parts[] = user.split("\\@");
//use different filter for email
filter = "(userPrincipalName="+user+")";
}
SearchControls ctrl = new SearchControls();
ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
ctrl.setReturningAttributes(requiredAttributes);
NamingEnumeration userInfo = null;
Integer i = 0;
do
{
userInfo = ctx.search(ADSearchPaths[i], filter, ctrl);
i++;
} while(!userInfo.hasMore() && i < ADSearchPaths.length );
if (userInfo.hasMore()) {
SearchResult UserDetails = (SearchResult) userInfo.next();
Attributes userAttr = UserDetails.getAttributes();System.out.println("adEmail = "+userAttr.get("userPrincipalName").get(0).toString());
System.out.println("adFirstName = "+userAttr.get("givenName").get(0).toString());
System.out.println("adLastName = "+userAttr.get("sn").get(0).toString());
System.out.println("name = "+userAttr.get("cn").get(0).toString());
System.out.println("AdFullName = "+userAttr.get("cn").get(0).toString());
}
userInfo.close();
}
catch (javax.naming.AuthenticationException e) {
}
}
}
Here is a short sub to parse a MicroStation Triforma XML file that contains data for structural steel shapes.
'location of triforma structural files
'c:\programdata\bentley\workspace\triforma\tf_imperial\data\us.xml
Sub ReadTriformaImperialData()
Dim txtFileName As String
Dim txtFileLine As String
Dim txtFileNumber As Long
Dim Shape As String
Shape = "w12x40"
txtFileNumber = FreeFile
txtFileName = "c:\programdata\bentley\workspace\triforma\tf_imperial\data\us.xml"
Open txtFileName For Input As #txtFileNumber
Do While Not EOF(txtFileNumber)
Line Input #txtFileNumber, txtFileLine
If InStr(1, UCase(txtFileLine), UCase(Shape)) Then
P1 = InStr(1, UCase(txtFileLine), "D=")
D = Val(Mid(txtFileLine, P1 + 3))
P2 = InStr(1, UCase(txtFileLine), "TW=")
TW = Val(Mid(txtFileLine, P2 + 4))
P3 = InStr(1, UCase(txtFileLine), "WIDTH=")
W = Val(Mid(txtFileLine, P3 + 7))
P4 = InStr(1, UCase(txtFileLine), "TF=")
TF = Val(Mid(txtFileLine, P4 + 4))
Close txtFileNumber
Exit Do
End If
Loop
End Sub
From here you can use the values to draw the shape in MicroStation 2d or do it in 3d and extrude it to a solid.
You can write a VBScript script to get the file version info:
VersionInfo.vbs
set args = WScript.Arguments
Set fso = CreateObject("Scripting.FileSystemObject")
WScript.Echo fso.GetFileVersion(args(0))
Wscript.Quit
You can call this from the command line like this:
cscript //nologo VersionInfo.vbs C:\Path\To\MyFile.dll
An Instant is what it says: a specific instant in time - it does not have the notion of date and time (the time in New York and Tokyo is not the same at a given instant).
To print it as a date/time, you first need to decide which timezone to use. For example:
System.out.println(LocalDateTime.ofInstant(i, ZoneOffset.UTC));
This will print the date/time in iso format: 2015-06-02T10:15:02.325
If you want a different format you can use a formatter:
LocalDateTime datetime = LocalDateTime.ofInstant(i, ZoneOffset.UTC);
String formatted = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss").format(datetime);
System.out.println(formatted);
Try:
$ rm YOUR_PROJECT_DIR/.metadata/.plugins/org.eclipse.core.resources/.snap
Original source: Job found still running after platform shutdown eclipse
If you use numpy
, this is easy:
slice = arr[:2,:2]
or if you want the 0's,
slice = arr[0:2,0:2]
You'll get the same result.
*note that slice
is actually the name of a builtin-type. Generally, I would advise giving your object a different "name".
Another way, if you're working with lists of lists*:
slice = [arr[i][0:2] for i in range(0,2)]
(Note that the 0's here are unnecessary: [arr[i][:2] for i in range(2)]
would also work.).
What I did here is that I take each desired row 1 at a time (arr[i]
). I then slice the columns I want out of that row and add it to the list that I'm building.
If you naively try: arr[0:2]
You get the first 2 rows which if you then slice again arr[0:2][0:2]
, you're just slicing the first two rows over again.
*This actually works for numpy arrays too, but it will be slow compared to the "native" solution I posted above.
This post was helpful to solve my problem which has a little different XML format... my XML contains a list of keys like the following example and I store the XML in the SourceKeys column in a table named DeleteBatch:
<k>1</k>
<k>2</k>
<k>3</k>
Create the table and populate it with some data:
CREATE TABLE dbo.DeleteBatch (
ExecutionKey INT PRIMARY KEY,
SourceKeys XML)
INSERT INTO dbo.DeleteBatch ( ExecutionKey, SourceKeys )
SELECT 1,
(CAST('<k>1</k><k>2</k><k>3</k>' AS XML))
INSERT INTO dbo.DeleteBatch ( ExecutionKey, SourceKeys )
SELECT 2,
(CAST('<k>100</k><k>101</k>' AS XML))
Here's my SQL to select the keys from the XML:
SELECT ExecutionKey, p.value('.', 'int') AS [Key]
FROM dbo.DeleteBatch
CROSS APPLY SourceKeys.nodes('/k') t(p)
Here's the query results...
ExecutionKey Key 1 1 1 2 1 3 2 100 2 101
You can write extention method:
public static async Task<Tout> ReadAsAsync<Tout>(this System.Net.Http.HttpContent content) {
return Newtonsoft.Json.JsonConvert.DeserializeObject<Tout>(await content.ReadAsStringAsync());
}
this error is also caused by null pointer reference. if you are using a pointer who is not initialized then it causes this error.
to check either a pointer is initialized or not you can try something like
Class *pointer = new Class();
if(pointer!=nullptr){
pointer->myFunction();
}
You should use formControlName="surveyType"
on an input
and not on a div
Regex ids = new Regex(@"\w*Id\b", RegexOptions.None);
\b
means "word break" and \w
means any word character. So \w*Id\b
means "{stuff}Id". By not including RegexOptions.IgnoreCase
, it will be case sensitive.
try this:
If Application.WorksheetFunction.CountIf(RangeToSearchIn, ValueToSearchFor) = 0 Then
Debug.Print "none"
End If
This error can occur especially when you are updating large libraries or libraries with a lot of dependencies. Composer can be quite memory hungry.
Be sure that your composer itself is updated to the latest version:
php composer.phar --self-update
You can increase the memory limit for composer temporarily by adding the composer memory limit environment variable:
COMPOSER_MEMORY_LIMIT=128MB php composer.phar update
Use the format “128M” for megabyte or “2G” for gigabyte. You can use the value “-1” to ignore the memory limit completely.
Another way would be to increase the PHP memory limit:
php -d memory_limit=512M composer.phar update ...
In the case of Android projects, you can fix this error by changing the project/module gradle file (build.gradle) as follows:
dependencies { implementation 'com.android.support:support-annotations:24.2.0' }
For more informations, please refer here.
The icons you are seeing on desktop is not a icon file. They are either executable files .exe or shortcuts of any application .lnk. So can only set icon which have .ico extension.
Go to Project Menu -> Your_Project_Name Properties -> Application TAB -> Resources -> Icon
browse for your Icon, remember it must have .ico extension
You can make your icon in Visual Studio
Go to Project Menu -> Add New Item -> Icon File
As a follow-up to the accepted answer, this is a minimal definition of the IHTMLScriptElement
interface which does not require to include additional type libraries:
[ComImport, ComVisible(true), Guid(@"3050f28b-98b5-11cf-bb82-00aa00bdce0b")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)]
[TypeLibType(TypeLibTypeFlags.FDispatchable)]
public interface IHTMLScriptElement
{
[DispId(1006)]
string text { set; [return: MarshalAs(UnmanagedType.BStr)] get; }
}
So a full code inside a WebBrowser control derived class would look like:
protected override void OnDocumentCompleted(
WebBrowserDocumentCompletedEventArgs e)
{
base.OnDocumentCompleted(e);
// Disable text selection.
var doc = Document;
if (doc != null)
{
var heads = doc.GetElementsByTagName(@"head");
if (heads.Count > 0)
{
var scriptEl = doc.CreateElement(@"script");
if (scriptEl != null)
{
var element = (IHTMLScriptElement)scriptEl.DomElement;
element.text =
@"function disableSelection()
{
document.body.onselectstart=function(){ return false; };
document.body.ondragstart=function() { return false; };
}";
heads[0].AppendChild(scriptEl);
doc.InvokeScript(@"disableSelection");
}
}
}
}
Here's one method you can use. This is the answer for one of FreeCodeCamp Challenges:
function truncateString(str, num) {
if (str.length > num) {
return str.slice(0, num) + "...";
} else {
return str;
}
}
var x;
if (x === undefined) {
alert ("I am declared, but not defined.")
};
if (typeof y === "undefined") {
alert ("I am not even declared.")
};
/* One more thing to understand: typeof ==='undefined' also checks
for if a variable is declared, but no value is assigned. In other
words, the variable is declared, but not defined. */
// Will repeat above logic of x for typeof === 'undefined'
if (x === undefined) {
alert ("I am declared, but not defined.")
};
/* So typeof === 'undefined' works for both, but x === undefined
only works for a variable which is at least declared. */
/* Say if I try using typeof === undefined (not in quotes) for
a variable which is not even declared, we will get run a
time error. */
if (z === undefined) {
alert ("I am neither declared nor defined.")
};
// I got this error for z ReferenceError: z is not defined
I have a nvidia GPU, and if nView is enabled it happens all the time. Try to disable it.
It seems that eclipse is not very compatible with softwares that override system window management on multi screen.
Hint how to disable nView: http://nviewdesktopmanager.blogspot.com/2011/08/how-to-disable-nview-desktop-manager.html
function get_domain($url = SITE_URL)
{
preg_match("/[a-z0-9\-]{1,63}\.[a-z\.]{2,6}$/", parse_url($url, PHP_URL_HOST), $_domain_tld);
return $_domain_tld[0];
}
get_domain('http://www.cdl.gr'); //cdl.gr
get_domain('http://cdl.gr'); //cdl.gr
get_domain('http://www2.cdl.gr'); //cdl.gr
If you want to plot a single line connecting all the points in the list
plt.plot(li[:])
plt.show()
This will plot a line connecting all the pairs in the list as points on a Cartesian plane from the starting of the list to the end. I hope that this is what you wanted.
You must specify which type the response is
this.productService.getProducts().subscribe(res => {
this.productsArray = res;
});
Try this
this.productService.getProducts().subscribe((res: Product[]) => {
this.productsArray = res;
});
You can use
Trace.WriteLine()
to write to the Output window when debugging a unit test.
You seem to be doing file name comparisons, so I would just add that OrdinalIgnoreCase
is closest to what NTFS does (it's not exactly the same, but it's closer than InvariantCultureIgnoreCase
)
Singleton scope in Spring means that this bean will be instantiated only once by Spring. In contrast to the prototype scope (new instance each time), request scope (once per request), session scope (once per HTTP session).
Singleton scope has technically nothing to do with the singleton design pattern. You don't have to implement your beans as singletons for them to be put in the singleton scope.
Here's the only solution so far for MacOS:
top -pid `pgrep java | awk 'ORS=" -pid "' | sed 's/.\{6\}$//'`
though this will undesirably report invalid option or syntax: -pid
if there are no java
processes alive.
EXPLANATION
The other solutions posted here use the format top -p id1,id2,id3
, but MacOS' top
only supports the unwieldy format top -pid id1 -pid id2 -pid id3
.
So firstly, we obtain the list of process ids which have process name "java":
pgrep java
and we pipe this to awk
which joins the results with delimitor " -pid "
| awk 'ORS=" -pid "'
Alas, this leaves a trailing delimitor! For example, we may so far have obtained the string "123 -pid 456 -pid 789 -pid "
.
We then just use sed
to shave off the final 6 characters of the delimitor.
| sed 's/.\{6\}$//'`
We're ready to pass the results to top
:
top -pid `...`
Here is the code,which worked for me.
Button buttonLoadImage = (Button) findViewById(R.id.button4);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.INTERNAL_CONTENT_URI);
intent.setType("image/*");
intent.putExtra("crop", "true");
intent.putExtra("scale", true);
intent.putExtra("outputX", 256);
intent.putExtra("outputY", 256);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("return-data", true);
startActivityForResult(intent, 1);}});
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_OK) {
if (requestCode == RESULT_LOAD_IMAGE && data != null) {
Uri imageUri = data.getData();
imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageURI(imageUri);}}}
in Manifest file add
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
One way to programmatically "click" the button, if you have access to the source, is to simply call the button's OnClick event handler (or Execute the ICommand associated with the button, if you're doing things in the more WPF-y manner).
Why are you doing this? Are you doing some sort of automated testing, for example, or trying to perform the same action that the button performs from a different section of code?
%hash1 = (%hash1, %hash2) ## or else ... @hash1{keys %hash2} = values %hash2; ## or with references ... $hash_ref1 = { %$hash_ref1, %$hash_ref2 };
undef
, zero, empty string, false
, falsy ...)1 * (aka associative-array, aka dictionary)
How can I roll back my previous 4 commits locally in a branch?
Which means, you are not creating new branch and going into detached state. New way of doing that is:
git switch --detach revison
For Windows Smart device (compact frame work ) (MC75-Motorola devices)
mytabControl.SelectedIndex = 1
That's aLL
While the currently accepted answer was a huge help to me, I wanted to share some useful modifications that simplify the queries and also increase performance.
To handle events which recur at regular intervals, such as:
Repeat every other day
or
Repeat every week on Tuesday
You should create two tables, one called events
like this:
ID NAME
1 Sample Event
2 Another Event
And a table called events_meta
like this:
ID event_id repeat_start repeat_interval
1 1 1369008000 604800 -- Repeats every Monday after May 20th 2013
1 1 1369008000 604800 -- Also repeats every Friday after May 20th 2013
With repeat_start
being a unix timestamp date with no time (1369008000 corresponds to May 20th 2013) , and repeat_interval
an amount in seconds between intervals (604800 is 7 days).
By looping over each day in the calendar you can get repeat events using this simple query:
SELECT EV.*
FROM `events` EV
RIGHT JOIN `events_meta` EM1 ON EM1.`event_id` = EV.`id`
WHERE (( 1299736800 - repeat_start) % repeat_interval = 0 )
Just substitute in the unix-timestamp (1299736800) for each date in your calendar.
Note the use of the modulo (% sign). This symbol is like regular division, but returns the ''remainder'' instead of the quotient, and as such is 0 whenever the current date is an exact multiple of the repeat_interval from the repeat_start.
This is significantly faster than the previously suggested "meta_keys"-based answer, which was as follows:
SELECT EV.*
FROM `events` EV
RIGHT JOIN `events_meta` EM1 ON EM1.`event_id` = EV.`id`
RIGHT JOIN `events_meta` EM2 ON EM2.`meta_key` = CONCAT( 'repeat_interval_', EM1.`id` )
WHERE EM1.meta_key = 'repeat_start'
AND (
( CASE ( 1299132000 - EM1.`meta_value` )
WHEN 0
THEN 1
ELSE ( 1299132000 - EM1.`meta_value` )
END
) / EM2.`meta_value`
) = 1
If you run EXPLAIN this query, you'll note that it required the use of a join buffer:
+----+-------------+-------+--------+---------------+---------+---------+------------------+------+--------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+--------+---------------+---------+---------+------------------+------+--------------------------------+
| 1 | SIMPLE | EM1 | ALL | NULL | NULL | NULL | NULL | 2 | Using where |
| 1 | SIMPLE | EV | eq_ref | PRIMARY | PRIMARY | 4 | bcs.EM1.event_id | 1 | |
| 1 | SIMPLE | EM2 | ALL | NULL | NULL | NULL | NULL | 2 | Using where; Using join buffer |
+----+-------------+-------+--------+---------------+---------+---------+------------------+------+--------------------------------+
The solution with 1 join above requires no such buffer.
You can add support for more complex types to support these types of repeat rules:
Event A repeats every month on the 3rd of the month starting on March 3, 2011
or
Event A repeats second Friday of the month starting on March 11, 2011
Your events table can look exactly the same:
ID NAME
1 Sample Event
2 Another Event
Then to add support for these complex rules add columns to events_meta
like so:
ID event_id repeat_start repeat_interval repeat_year repeat_month repeat_day repeat_week repeat_weekday
1 1 1369008000 604800 NULL NULL NULL NULL NULL -- Repeats every Monday after May 20, 2013
1 1 1368144000 604800 NULL NULL NULL NULL NULL -- Repeats every Friday after May 10, 2013
2 2 1369008000 NULL 2013 * * 2 5 -- Repeats on Friday of the 2nd week in every month
Note that you simply need to either specify a repeat_interval
or a set of repeat_year
, repeat_month
, repeat_day
, repeat_week
, and repeat_weekday
data.
This makes selection of both types simultaneously very simple. Just loop through each day and fill in the correct values, (1370563200 for June 7th 2013, and then the year, month, day, week number and weekday as follows):
SELECT EV.*
FROM `events` EV
RIGHT JOIN `events_meta` EM1 ON EM1.`event_id` = EV.`id`
WHERE (( 1370563200 - repeat_start) % repeat_interval = 0 )
OR (
(repeat_year = 2013 OR repeat_year = '*' )
AND
(repeat_month = 6 OR repeat_month = '*' )
AND
(repeat_day = 7 OR repeat_day = '*' )
AND
(repeat_week = 2 OR repeat_week = '*' )
AND
(repeat_weekday = 5 OR repeat_weekday = '*' )
AND repeat_start <= 1370563200
)
This returns all events that repeat on the Friday of the 2nd week, as well as any events that repeat every Friday, so it returns both event ID 1 and 2:
ID NAME
1 Sample Event
2 Another Event
*Sidenote in the above SQL I used PHP Date's default weekday indexes, so "5" for Friday
Hope this helps others as much as the original answer helped me!
Swift 5.1 Custom Object/Type
// MARK: - NotificationName
// Extending notification name to avoid string errors.
extension Notification.Name {
static let yourNotificationName = Notification.Name("yourNotificationName")
}
// MARK: - CustomObject
class YourCustomObject {
// Any stuffs you would like to set in your custom object as always.
init() {}
}
// MARK: - Notification Sender Class
class NotificatioSenderClass {
// Just grab the content of this function and put it to your function responsible for triggering a notification.
func postNotification(){
// Note: - This is the important part pass your object instance as object parameter.
let yourObjectInstance = YourCustomObject()
NotificationCenter.default.post(name: .yourNotificationName, object: yourObjectInstance)
}
}
// MARK: -Notification Receiver class
class NotificationReceiverClass: UIViewController {
// MARK: - ViewController Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// Register your notification listener
NotificationCenter.default.addObserver(self, selector: #selector(didReceiveNotificationWithCustomObject), name: .yourNotificationName, object: nil)
}
// MARK: - Helpers
@objc private func didReceiveNotificationWithCustomObject(notification: Notification){
// Important: - Grab your custom object here by casting the notification object.
guard let yourPassedObject = notification.object as? YourCustomObject else {return}
// That's it now you can use your custom object
//
//
}
// MARK: - Deinit
deinit {
// Save your memory by releasing notification listener
NotificationCenter.default.removeObserver(self, name: .yourNotificationName, object: nil)
}
}
You should use the optional argument indent
.
header, output = client.request(twitterRequest, method="GET", body=None,
headers=None, force_auth_header=True)
# now write output to a file
twitterDataFile = open("twitterData.json", "w")
# magic happens here to make it pretty-printed
twitterDataFile.write(simplejson.dumps(simplejson.loads(output), indent=4, sort_keys=True))
twitterDataFile.close()
A simple example for one task:
using System;
using System.Timers;
namespace ConsoleApp
{
internal class Scheduler
{
private static readonly DateTime scheduledTime =
new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 10, 0, 0);
private static DateTime dateTimeLastRunTask;
internal static void CheckScheduledTask()
{
if (dateTimeLastRunTask.Date < DateTime.Today && scheduledTime.TimeOfDay < DateTime.Now.TimeOfDay)
{
Console.WriteLine("Time to run task");
dateTimeLastRunTask = DateTime.Now;
}
else
{
Console.WriteLine("not yet time");
}
}
}
internal class Program
{
private static Timer timer;
static void Main(string[] args)
{
timer = new Timer(5000);
timer.Elapsed += OnTimer;
timer.Start();
Console.ReadLine();
}
private static void OnTimer(object source, ElapsedEventArgs e)
{
Scheduler.CheckScheduledTask();
}
}
}
I had enough success just catchig socket.timeout
and socket.error
; although socket.error can be raised for lots of reasons. Be careful.
import socket
import logging
hostname='google.com'
port=443
try:
sock = socket.create_connection((hostname, port), timeout=3)
except socket.timeout as err:
logging.error(err)
except socket.error as err:
logging.error(err)
Sass supports @if
statements. (See the documentation.)
You could write your mixin like this:
@mixin box-shadow($top, $left, $blur, $color, $inset:"") {
@if $inset != "" {
-webkit-box-shadow:$top $left $blur $color $inset;
-moz-box-shadow:$top $left $blur $color $inset;
box-shadow:$top $left $blur $color $inset;
}
}
If there are no spaces in paths, and you are interested, like I was, in files of specific extension only, you can use
git checkout otherBranch -- $(git ls-tree --name-only -r otherBranch | egrep '*.java')
If you only want the tag names, it should be possible to do this via a regular expression.
<([a-zA-Z]+)(?:[^>]*[^/] *)?>
should do what you need. But I think the solution of "moritz" is already fine. I didn't see it in the beginning.
For all downvoters: In some cases it just makes sense to use a regular expression, because it can be the easiest and quickest solution. I agree that in general you should not parse HTML with regular expressions.
But regular expressions can be a very powerful tool when you have a subset of HTML where you know the format and you just want to extract some values. I did that hundreds of times and almost always achieved what I wanted.
You can use an RDLC file provided in visual studio to define your report layout. You can view the rdlc using the ReportViewer control.
Both are provided out of the box with visual studio.
a more precise way for employee paid hours or other precision requirement::
decimal DeterminePreciseHours(DateTime startTimestamp, DateTime stopTimestamp)
{
var span = (stopTimestamp - startTimestamp).Value;
decimal total = (decimal)span.TotalMilliseconds / 60 / 60 / 1000;
return Math.Round(total, PRECISION_CONSTANT);
}
When you
Mojave 10.14.6
/usr/include
was deleted againThe file /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg does not exist.
andxcode-select --install
xcode-select: error: command line tools are already installed, use "Software Update" to install updates
Then, what helped me recover the mentioned package, was deleting the whole CommandLineTools
folder
(sudo) rm -rf /Library/Developer/CommandLineTools
and reinstall it xcode-select --install
.
It is safe to store your token in localStorage as long as you encrypt it. Below is a compressed code snippet showing one of many ways you can do it.
import SimpleCrypto from 'simple-crypto-js';
const saveToken = (token = '') => {
const encryptInit = new SimpleCrypto('PRIVATE_KEY_STORED_IN_ENV_FILE');
const encryptedToken = encryptInit.encrypt(token);
localStorage.setItem('token', encryptedToken);
}
Then, before using your token decrypt it using PRIVATE_KEY_STORED_IN_ENV_FILE
Simplest way to get everything working in RStudio under Windows 10
:
Open up Internet Explorer, select Internet Options
:
Open editor for Environment variables:
Add a variable HTTP_PROXY in form:
HTTP_PROXY=http://username:password@localhost:port/
Example:
HTTP_PROXY=http://John:JohnPassword@localhost:8080/
RStudio should work:
For example, a logout button can be written like this:
<button class="btn btn-primary" onclick="location.href={% url 'logout'%}">Logout</button>
Where logout endpoint:
#urls.py:
url(r'^logout/$', auth_views.logout, {'next_page': '/'}, name='logout'),
If you have .NET v4 installed (so if you have a newer windows or if you apply the windows updates)
C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe somefile.cs
or
C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe nomefile.sln
or
C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe nomefile.csproj
It's highly probable that if you have .NET installed, the %FrameworkDir%
variable is set, so:
%FrameworkDir%\v4.0.30319\csc.exe ...
%FrameworkDir%\v4.0.30319\msbuild.exe ...
For whatever reason, the Scanner class also issues this same exception if it encounters special characters it cannot read. Beyond using the hasNextLine()
method before each call to nextLine()
, make sure the correct encoding is passed to the Scanner
constructor, e.g.:
Scanner scanner = new Scanner(new FileInputStream(filePath), "UTF-8");
I have written down the steps:
? Add gem 'newrelic_rpm' to your Gemfile under staging & production
? bundle install
? Login to heroku control panel and add newrelic addon
? Once added, setup automatic pinging to your website so that it does not idle
? Browse to Menu > Availability Monitoring (under Settings)
? Click “Turn on Availability Monitoring”
? Enter the url to ping (eg: http://spokenvote.org)
? Select 1 minute for the interval
The BIT
datatype is generally used to store boolean
values (0
for false
, 1
for true
).
Expanding on @jake's answer, the transition will go all the way to the max height value, causing an extremely fast animation - if you set the transitions for both :hover and off you can then control the crazy speed a little bit more.
So the li:hover is when the mouse enters the state and then the transition on the non-hovered property will be the mouse leave.
Hopefully this will be of some help.
e.g:
.sidemenu li ul {
max-height: 0px;
-webkit-transition: all .3s ease;
-moz-transition: all .3s ease;
-o-transition: all .3s ease;
-ms-transition: all .3s ease;
transition: all .3s ease;
}
.sidemenu li:hover ul {
max-height: 500px;
-webkit-transition: all 1s ease;
-moz-transition: all 1s ease;
-o-transition: all 1s ease;
-ms-transition: all 1s ease;
transition: all 1s ease;
}
/* Adjust speeds to the possible height of the list */
Here's a fiddle: http://jsfiddle.net/BukwJ/
Here you go, using Generics
:
private <T> T getRandomItem(List<T> list)
{
Random random = new Random();
int listSize = list.size();
int randomIndex = random.nextInt(listSize);
return list.get(randomIndex);
}
=INDEX(GoogleFinance("CURRENCY:" & "EUR" & "USD", "price", A2), 2, 2)
where A2
is the cell with a date formatted as date.
Replace "EUR" and "USD" with your currency pair.
Right click your project--->Build path---->configure Build path----> Libraries Tab--->Add External jars--->(Navigate to the location where you have kept the sql driver jar)--->ok
You could use the **\**
character before the value you want to escape e.g
insert into msglog(recipient) values('Mr. O\'riely')
select * from msglog where recipient = 'Mr. O\'riely'
why dont you add a "source" column to each of the queries with a static value like
select 'source 1' as Source, column1, column2...
from table1
UNION ALL
select 'source 2' as Source, column1, column2...
from table2
Set the socket non-blocking, and use select()
(which takes a timeout parameter). If a non-blocking socket is trying to connect, then select()
will indicate that the socket is writeable when the connect()
finishes (either successfully or unsuccessfully). You then use getsockopt()
to determine the outcome of the connect()
:
int main(int argc, char **argv) {
u_short port; /* user specified port number */
char *addr; /* will be a pointer to the address */
struct sockaddr_in address; /* the libc network address data structure */
short int sock = -1; /* file descriptor for the network socket */
fd_set fdset;
struct timeval tv;
if (argc != 3) {
fprintf(stderr, "Usage %s <port_num> <address>\n", argv[0]);
return EXIT_FAILURE;
}
port = atoi(argv[1]);
addr = argv[2];
address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr(addr); /* assign the address */
address.sin_port = htons(port); /* translate int2port num */
sock = socket(AF_INET, SOCK_STREAM, 0);
fcntl(sock, F_SETFL, O_NONBLOCK);
connect(sock, (struct sockaddr *)&address, sizeof(address));
FD_ZERO(&fdset);
FD_SET(sock, &fdset);
tv.tv_sec = 10; /* 10 second timeout */
tv.tv_usec = 0;
if (select(sock + 1, NULL, &fdset, NULL, &tv) == 1)
{
int so_error;
socklen_t len = sizeof so_error;
getsockopt(sock, SOL_SOCKET, SO_ERROR, &so_error, &len);
if (so_error == 0) {
printf("%s:%d is open\n", addr, port);
}
}
close(sock);
return 0;
}
Similar error as well. Realized I had an .htpasswd setup for the particular host. Uncommented it from the .htaccess file and worked fine.
After some trial and tribulation, I was able to find all .msi files in a given directory and install them.
foreach($_msiFiles in
($_msiFiles = Get-ChildItem $_Source -Recurse | Where{$_.Extension -eq ".msi"} |
Where-Object {!($_.psiscontainter)} | Select-Object -ExpandProperty FullName))
{
msiexec /i $_msiFiles /passive
}
When you do return Json(...)
you are specifically telling MVC not to use a view, and to serve serialized JSON data. Your browser opens a download dialog because it doesn't know what to do with this data.
If you instead want to return a view, just do return View(...)
like you normally would:
var dictionary = listLocation.ToDictionary(x => x.label, x => x.value);
return View(new { Values = listLocation });
Then in your view, simply encode your data as JSON and assign it to a JavaScript variable:
<script>
var values = @Html.Raw(Json.Encode(Model.Values));
</script>
EDIT
Here is a bit more complete sample. Since I don't have enough context from you, this sample will assume a controller Foo
, an action Bar
, and a view model FooBarModel
. Additionally, the list of locations is hardcoded:
Controllers/FooController.cs
public class FooController : Controller
{
public ActionResult Bar()
{
var locations = new[]
{
new SelectListItem { Value = "US", Text = "United States" },
new SelectListItem { Value = "CA", Text = "Canada" },
new SelectListItem { Value = "MX", Text = "Mexico" },
};
var model = new FooBarModel
{
Locations = locations,
};
return View(model);
}
}
Models/FooBarModel.cs
public class FooBarModel
{
public IEnumerable<SelectListItem> Locations { get; set; }
}
Views/Foo/Bar.cshtml
@model MyApp.Models.FooBarModel
<script>
var locations = @Html.Raw(Json.Encode(Model.Locations));
</script>
By the looks of your error message, it seems like you are mixing incompatible types (i.e. Ported_LI.Models.Locatio??n
and MyApp.Models.Location
) so, to recap, make sure the type sent from the controller action side match what is received from the view. For this sample in particular, new FooBarModel
in the controller matches @model MyApp.Models.FooBarModel
in the view.
Select the version you're using and it will give you a step by step guide.
I recommend choosing 'Advanced' to see all steps. Complexity is a relative concept - and I don't know whose stupid idea this feature was, but if you select 'Basic' it won't show you all steps needed and you may miss something important that your otherwise 'Basic' application is using.
As of version 6 there is a new Angular CLI command ng update
which intelligently goes through your dependencies and performs checks to make sure you're updating the right things :-)
The steps will outline how to use it :-)
In cases when a parameter name cannot be hardcoded I found this would be the simplest and best way to access parameters:
def myParam = env.getProperty(dynamicParamName)
In cases, when a parameter name is known and can be hardcoded the following 3 lines are equivalent:
def myParam = env.getProperty("myParamName")
def myParam = env.myParamName
def myParam = myParamName
If you have Visual Studio installed, you will find it comes with its own copy of node separate from the one that is on the path when you installed node yourself - Mine is in C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Microsoft\VisualStudio\NodeJs.
If you run the npm command from inside this directory you will find out which node modules are installed inside visual studio.
I have created a version of the accepted answer that works with both '[Serializable]' and '[DataContract]'. It has been a while since I wrote it, but if I remember correctly [DataContract] needed a different serializer.
Requires System, System.IO, System.Runtime.Serialization, System.Runtime.Serialization.Formatters.Binary, System.Xml;
public static class ObjectCopier
{
/// <summary>
/// Perform a deep Copy of an object that is marked with '[Serializable]' or '[DataContract]'
/// </summary>
/// <typeparam name="T">The type of object being copied.</typeparam>
/// <param name="source">The object instance to copy.</param>
/// <returns>The copied object.</returns>
public static T Clone<T>(T source)
{
if (typeof(T).IsSerializable == true)
{
return CloneUsingSerializable<T>(source);
}
if (IsDataContract(typeof(T)) == true)
{
return CloneUsingDataContracts<T>(source);
}
throw new ArgumentException("The type must be Serializable or use DataContracts.", "source");
}
/// <summary>
/// Perform a deep Copy of an object that is marked with '[Serializable]'
/// </summary>
/// <remarks>
/// Found on http://stackoverflow.com/questions/78536/cloning-objects-in-c-sharp
/// Uses code found on CodeProject, which allows free use in third party apps
/// - http://www.codeproject.com/KB/tips/SerializedObjectCloner.aspx
/// </remarks>
/// <typeparam name="T">The type of object being copied.</typeparam>
/// <param name="source">The object instance to copy.</param>
/// <returns>The copied object.</returns>
public static T CloneUsingSerializable<T>(T source)
{
if (!typeof(T).IsSerializable)
{
throw new ArgumentException("The type must be serializable.", "source");
}
// Don't serialize a null object, simply return the default for that object
if (Object.ReferenceEquals(source, null))
{
return default(T);
}
IFormatter formatter = new BinaryFormatter();
Stream stream = new MemoryStream();
using (stream)
{
formatter.Serialize(stream, source);
stream.Seek(0, SeekOrigin.Begin);
return (T)formatter.Deserialize(stream);
}
}
/// <summary>
/// Perform a deep Copy of an object that is marked with '[DataContract]'
/// </summary>
/// <typeparam name="T">The type of object being copied.</typeparam>
/// <param name="source">The object instance to copy.</param>
/// <returns>The copied object.</returns>
public static T CloneUsingDataContracts<T>(T source)
{
if (IsDataContract(typeof(T)) == false)
{
throw new ArgumentException("The type must be a data contract.", "source");
}
// ** Don't serialize a null object, simply return the default for that object
if (Object.ReferenceEquals(source, null))
{
return default(T);
}
DataContractSerializer dcs = new DataContractSerializer(typeof(T));
using(Stream stream = new MemoryStream())
{
using (XmlDictionaryWriter writer = XmlDictionaryWriter.CreateBinaryWriter(stream))
{
dcs.WriteObject(writer, source);
writer.Flush();
stream.Seek(0, SeekOrigin.Begin);
using (XmlDictionaryReader reader = XmlDictionaryReader.CreateBinaryReader(stream, XmlDictionaryReaderQuotas.Max))
{
return (T)dcs.ReadObject(reader);
}
}
}
}
/// <summary>
/// Helper function to check if a class is a [DataContract]
/// </summary>
/// <param name="type">The type of the object to check.</param>
/// <returns>Boolean flag indicating if the class is a DataContract (true) or not (false) </returns>
public static bool IsDataContract(Type type)
{
object[] attributes = type.GetCustomAttributes(typeof(DataContractAttribute), false);
return attributes.Length == 1;
}
}
dat1 and dat2 are Strings in JavaScript. There is no getTime function on the String prototype. I believe you want the Date.parse() function: http://www.w3schools.com/jsref/jsref_parse.asp
You would use it like this:
var date = Date.parse(dat1);
I use to store it in a file:
int pid = android.os.Process.myPid();
File outputFile = new File(Environment.getExternalStorageDirectory() + "/logs/logcat.txt");
try {
String command = "logcat | grep " + pid + " > " + outputFile.getAbsolutePath();
Process p = Runtime.getRuntime().exec("su");
OutputStream os = p.getOutputStream();
os.write((command + "\n").getBytes("ASCII"));
} catch (IOException e) {
e.printStackTrace();
}
In ssms we can use GO to execute same statement
Edit This mean if you put
some query
GO n
Some query will be executed n times
I think that. When guest is launching page, but Admin is not logged in we don`t show something, for example the Chat.
add_action('init', 'chat_status');
function chat_status(){
if( get_option('admin_logged') === 1) { echo "<style>.chat{display:block;}</style>";}
else { echo "<style>.chat{display:none;}</style>";}
}
add_action('wp_login', function(){
if( wp_get_current_user()->roles[0] == 'administrator' ) update_option('admin_logged', 1);
});
add_action('wp_logout', function(){
if( wp_get_current_user()->roles[0] == 'administrator' ) update_option('admin_logged', 0);
});
The proper solution to resolve this issue is by following the steps
. Update Visual studio if you have older version to 15.5.4 (Optional)
Remove all binding redirects from web.config
Add this to the csproj file:
<PropertyGroup> <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects> <GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType> </PropertyGroup>
Build.
In the bin folder, there should be a (WebAppName).dll.config
file.
It should have redirects in it. Copy these to the web.config
Remove the above snipped from the csproj file again
It should work
var string="<script>...</script>";
string=encodeURIComponent(string); // %3Cscript%3E...%3C/script%3
>>> l = range(1,10)
>>> l
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> l[:2]
[1, 2]
>>> l[3:]
[4, 5, 6, 7, 8, 9]
>>> l[:2] + l[3:]
[1, 2, 4, 5, 6, 7, 8, 9]
>>>
See also
Use the below css to solve your issue
#footer{ text-align:center; height:58px;}
#footer ul { font-size:11px;}
#footer ul li {display:inline-block;}
Note: Don't use float:left
in li. it will make your li to align left.
Make sure you're in the right database context in SSMS. Got the same error as you, but I knew the schema already existed. Didn't realize I was in 'MASTER' context. ALTER worked after I changed context to my database.
In your controller class, create an action method you will hook the button up to in Interface Builder. Inside that method you can trim your string like this:
if ([string length] > 0) {
string = [string substringToIndex:[string length] - 1];
} else {
//no characters to delete... attempting to do so will result in a crash
}
If you want a fancy way of doing this in just one line of code you could write it as:
string = [string substringToIndex:string.length-(string.length>0)];
*Explanation of fancy one-line code snippet:
If there is a character to delete (i.e. the length of the string is greater than 0)
(string.length>0)
returns 1
thus making the code return:
string = [string substringToIndex:string.length-1];
If there is NOT a character to delete (i.e. the length of the string is NOT greater than 0)
(string.length>0)
returns 0
thus making the code return:
string = [string substringToIndex:string.length-0];
Which prevents crashes.
IMHO better than the accepted answer is to use the following:
git config --local status.showUntrackedFiles no
The accepted answer does not work for when new files are added that are not in .gitignore
CMake honors the environment variables CC
and CXX
upon detecting the C and C++ compiler to use:
$ export CC=/usr/bin/clang
$ export CXX=/usr/bin/clang++
$ cmake ..
-- The C compiler identification is Clang
-- The CXX compiler identification is Clang
The compiler specific flags can be overridden by putting them into a make override file and pointing the CMAKE_USER_MAKE_RULES_OVERRIDE
variable to it. Create a file ~/ClangOverrides.txt
with the following contents:
SET (CMAKE_C_FLAGS_INIT "-Wall -std=c99")
SET (CMAKE_C_FLAGS_DEBUG_INIT "-g")
SET (CMAKE_C_FLAGS_MINSIZEREL_INIT "-Os -DNDEBUG")
SET (CMAKE_C_FLAGS_RELEASE_INIT "-O3 -DNDEBUG")
SET (CMAKE_C_FLAGS_RELWITHDEBINFO_INIT "-O2 -g")
SET (CMAKE_CXX_FLAGS_INIT "-Wall")
SET (CMAKE_CXX_FLAGS_DEBUG_INIT "-g")
SET (CMAKE_CXX_FLAGS_MINSIZEREL_INIT "-Os -DNDEBUG")
SET (CMAKE_CXX_FLAGS_RELEASE_INIT "-O3 -DNDEBUG")
SET (CMAKE_CXX_FLAGS_RELWITHDEBINFO_INIT "-O2 -g")
The suffix _INIT
will make CMake initialize the corresponding *_FLAGS
variable with the given value. Then invoke cmake
in the following way:
$ cmake -DCMAKE_USER_MAKE_RULES_OVERRIDE=~/ClangOverrides.txt ..
Finally to force the use of the LLVM binutils, set the internal variable _CMAKE_TOOLCHAIN_PREFIX
. This variable is honored by the CMakeFindBinUtils
module:
$ cmake -D_CMAKE_TOOLCHAIN_PREFIX=llvm- ..
Putting this all together you can write a shell wrapper which sets up the environment variables CC
and CXX
and then invokes cmake
with the mentioned variable overrides.
Also see this CMake FAQ on make override files.
My version of @Merak Marey's Code. I am checking if files exist already and different download directories for .txt and other files
static void DownloadAll()
{
string host = "xxx.xxx.xxx.xxx";
string username = "@@@";
string password = "123";string remoteDirectory = "/IN/";
string finalDir = "";
string localDirectory = @"C:\filesDN\";
string localDirectoryZip = @"C:\filesDN\ZIP\";
using (var sftp = new SftpClient(host, username, password))
{
Console.WriteLine("Connecting to " + host + " as " + username);
sftp.Connect();
Console.WriteLine("Connected!");
var files = sftp.ListDirectory(remoteDirectory);
foreach (var file in files)
{
string remoteFileName = file.Name;
if ((!file.Name.StartsWith(".")) && ((file.LastWriteTime.Date == DateTime.Today)))
{
if (!file.Name.Contains(".TXT"))
{
finalDir = localDirectoryZip;
}
else
{
finalDir = localDirectory;
}
if (File.Exists(finalDir + file.Name))
{
Console.WriteLine("File " + file.Name + " Exists");
}else{
Console.WriteLine("Downloading file: " + file.Name);
using (Stream file1 = File.OpenWrite(finalDir + remoteFileName))
{
sftp.DownloadFile(remoteDirectory + remoteFileName, file1);
}
}
}
}
Console.ReadLine();
}
I've used the solution described here http://jtruher.spaces.live.com/blog/cns!7143DA6E51A2628D!130.entry successfully in PowerShell v1.0. It definitely will be easier in PowerShell v2.0.
You should always use below MIME type if you want to serve excel file in xlsx format
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
Use count(d.ertek)
or count(d.id)
instead of count(d)
. This can be happen when you have composite primary key at your entity.
try something like this
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle("select folder");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
You have to give the dictionary a type
// empty dict with Ints as keys and Strings as values
var namesOfIntegers = Dictionary<Int, String>()
If the compiler can infer the type, you can use the shorter syntax
namesOfIntegers[16] = "sixteen"
// namesOfIntegers now contains 1 key-value pair
namesOfIntegers = [:]
// namesOfIntegers is once again an empty dictionary of type Int, String
Notice, that if your module dependency has different flavors, you should use one of the strategies:
Like that:
dependencies {
compile project(path: ':module', configuration:'alphaDebug')
}
Pass the decode pattern to ParseExact
Dim d as string = "201210120956"
Dim dt = DateTime.ParseExact(d, "yyyyMMddhhmm", Nothing)
ParseExact is available only from Net FrameWork 2.0.
If you are still on 1.1 you could use Parse, but you need to provide the IFormatProvider adequate to your string
In our case it ended up being a Kerberos issue. I followed the steps in this article to resolve the issue: https://techcommunity.microsoft.com/t5/SQL-Server-Support/Bulk-Insert-and-Kerberos/ba-p/317304.
It came down to configuring delegation on the machine account of the SQL Server where the BULK INSERT statement is running. The machine account needs to be able to delegate via the "cifs" service to the file server where the files are located. If you are using constrained delegation make sure to specify "Use any authenication protocol".
If DFS is involved you can execute the following Powershell command to get the name of the file server:
Get-DfsnFolderTarget -Path "\\dfsnamespace\share"
But there is switch-case :)
switch (true) {
case true:
console.log("Yes, its ture :) Break from the switch-case");
break;
case false:
console.log("Nope, but if the condition was set to false this would be used and then break");
break;
default:
console.log("If all else fails");
break;
}