It may be a bit late, but this is now easier to do in Pandas by calling Series.str.match
. The docs explain the difference between match
, fullmatch
and contains
.
Note that in order to use the results for indexing, set the na=False
argument (or True
if you want to include NANs in the results).
I had the same problem and tried all possible solution. But finally I came to know from the documentation that ngRoute
module is now separated. Have a look to this link
Solution: Add the cdn angular-route.js after angular.min.js script
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js"></script>
In MVC3 they've added this.
But whats even more nice is that since MVC source code is open you can grab the ValueProvider and use it yourself in your own code (if youre not on MVC3 yet).
You will end up with something like this
ValueProviderFactories.Factories.Add(new JsonValueProviderFactory())
You can use this configuration:
-startup
plugins/org.eclipse.equinox.launcher_1.3.0.v20120522-1813.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.1.200.v20120913-144807
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
-vmargs
-Xms512m
-Xmx1024m
-XX:+UseParallelGC
-XX:PermSize=256M
-XX:MaxPermSize=512M
Installing libgl1-mesa-dev from the Ubuntu repo resolved this problem for me.
Use OOP concept instead. Create a class with function
class MyClass {
...
function getData($query) {
$result = mysqli_query($this->conn, $query);
while($row=mysqli_fetch_assoc($result)) {
$resultset[] = $row;
}
if(!empty($resultset))
return $resultset;
} }
and then use the class object to call function in your code
<?php
$obj = new MyClass();
$row = $obj->getData("select city_name from city");
?>
<select>
<?php foreach($row as $row){ ?>
<option><?php echo $row['city_name'] ?></option>
<?php } ?>
</select>
Like this its work if you want to parse some string which is coming from mYearInDB.toString() =[2013] it will give 2013
Matcher n = MY_PATTERN.matcher("FOO[BAR]"+mYearInDB.toString());
while (n.find()) {
extracredYear = n.group(1);
// s now contains "BAR"
}
System.out.println("Extrated output is : "+extracredYear);
Here is a sample I wrote shows how I parse a json and mess every number inside it:
public class JsonParser {
public static Object parseAndMess(Object object) throws IOException {
String json = JsonUtil.toJson(object);
JsonNode jsonNode = parseAndMess(json);
if(null != jsonNode)
return JsonUtil.toObject(jsonNode, object.getClass());
return null;
}
public static JsonNode parseAndMess(String json) throws IOException {
JsonNode rootNode = parse(json);
return mess(rootNode, new Random());
}
private static JsonNode parse(String json) throws IOException {
JsonFactory factory = new JsonFactory();
ObjectMapper mapper = new ObjectMapper(factory);
JsonNode rootNode = mapper.readTree(json);
return rootNode;
}
private static JsonNode mess(JsonNode rootNode, Random rand) throws IOException {
if (rootNode instanceof ObjectNode) {
Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
while (fieldsIterator.hasNext()) {
Map.Entry<String, JsonNode> field = fieldsIterator.next();
replaceObjectNode((ObjectNode) rootNode, field, rand);
}
} else if (rootNode instanceof ArrayNode) {
ArrayNode arrayNode = ((ArrayNode) rootNode);
replaceArrayNode(arrayNode, rand);
}
return rootNode;
}
private static void replaceObjectNode(ObjectNode rootNode, Map.Entry<String, JsonNode> field, Random rand)
throws IOException {
JsonNode childNode = field.getValue();
if (childNode instanceof IntNode) {
(rootNode).put(field.getKey(), rand.nextInt(1000));
} else if (childNode instanceof LongNode) {
(rootNode).put(field.getKey(), rand.nextInt(1000000));
} else if (childNode instanceof FloatNode) {
(rootNode).put(field.getKey(), format(rand.nextFloat()));
} else if (childNode instanceof DoubleNode) {
(rootNode).put(field.getKey(), format(rand.nextFloat()));
} else {
mess(childNode, rand);
}
}
private static void replaceArrayNode(ArrayNode arrayNode, Random rand) throws IOException {
int arrayLength = arrayNode.size();
if(arrayLength == 0)
return;
if (arrayNode.get(0) instanceof IntNode) {
for (int i = 0; i < arrayLength; i++) {
arrayNode.set(i, new IntNode(rand.nextInt(10000)));
}
} else if (arrayNode.get(0) instanceof LongNode) {
arrayNode.removeAll();
for (int i = 0; i < arrayLength; i++) {
arrayNode.add(rand.nextInt(1000000));
}
} else if (arrayNode.get(0) instanceof FloatNode) {
arrayNode.removeAll();
for (int i = 0; i < arrayLength; i++) {
arrayNode.add(format(rand.nextFloat()));
}
} else if (arrayNode.get(0) instanceof DoubleNode) {
arrayNode.removeAll();
for (int i = 0; i < arrayLength; i++) {
arrayNode.add(format(rand.nextFloat()));
}
} else {
for (int i = 0; i < arrayLength; i++) {
mess(arrayNode.get(i), rand);
}
}
}
public static void print(JsonNode rootNode) throws IOException {
System.out.println(rootNode.toString());
}
private static double format(float a) {
return Math.round(a * 10000.0) / 100.0;
}
}
grep -A 10000000 'TERMINATE' file
If you are using time.time()
and wants timestamp as output
Simply use
CONSTANT_SECONDS = 900 # time in seconds (900 seconds = 15 min)
current_time = int(time.time())
time_before_15_min = current_time - CONSTANT_SECONDS
You can change 900 seconds as per your required time.
Read line by line, not the whole file:
for line in open(file_name, 'rb'):
# process line here
Even better use with
for automatically closing the file:
with open(file_name, 'rb') as f:
for line in f:
# process line here
The above will read the file object using an iterator, one line at a time.
I think the best way is to prevent right clicking on your webpage, because that is the most convenient way a normal user try to download the content, and you can consider it as remark if u able to do this only as you are never gonna be able to stop a computer geek or hacker people from downloading it, because once the content is on the internet, it means it is in the public domain already...
MappedBy signals hibernate that the key for the relationship is on the other side.
This means that although you link 2 tables together, only 1 of those tables has a foreign key constraint to the other one. MappedBy allows you to still link from the table not containing the constraint to the other table.
public void postData(String url,JSONObject obj) {
// Create a new HttpClient and Post Header
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, 10000);
HttpConnectionParams.setSoTimeout(myParams, 10000);
HttpClient httpclient = new DefaultHttpClient(myParams );
String json=obj.toString();
try {
HttpPost httppost = new HttpPost(url.toString());
httppost.setHeader("Content-type", "application/json");
StringEntity se = new StringEntity(obj.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
String temp = EntityUtils.toString(response.getEntity());
Log.i("tag", temp);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
}
If you append json data to query string, and parse it later in web api side. you can parse complex object. It's useful rather than post json object style. This is my solution.
//javascript file
var data = { UserID: "10", UserName: "Long", AppInstanceID: "100", ProcessGUID: "BF1CC2EB-D9BD-45FD-BF87-939DD8FF9071" };
var request = JSON.stringify(data);
request = encodeURIComponent(request);
doAjaxGet("/ProductWebApi/api/Workflow/StartProcess?data=", request, function (result) {
window.console.log(result);
});
//webapi file:
[HttpGet]
public ResponseResult StartProcess()
{
dynamic queryJson = ParseHttpGetJson(Request.RequestUri.Query);
int appInstanceID = int.Parse(queryJson.AppInstanceID.Value);
Guid processGUID = Guid.Parse(queryJson.ProcessGUID.Value);
int userID = int.Parse(queryJson.UserID.Value);
string userName = queryJson.UserName.Value;
}
//utility function:
public static dynamic ParseHttpGetJson(string query)
{
if (!string.IsNullOrEmpty(query))
{
try
{
var json = query.Substring(7, query.Length - 7); //seperate ?data= characters
json = System.Web.HttpUtility.UrlDecode(json);
dynamic queryJson = JsonConvert.DeserializeObject<dynamic>(json);
return queryJson;
}
catch (System.Exception e)
{
throw new ApplicationException("can't deserialize object as wrong string content!", e);
}
}
else
{
return null;
}
}
This means you are mapping a column twice in your entity class. Explaining with an example...
@Column(name = "column1")
private String object1;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "column1", referencedColumnName = "column1")
private TableClass object2;
The problem in the above code snippet is we are repeating mapping...
Solution
Since mapping is an important part, you don't want to remove that. Instead, you will remove
@Column(name = "column1")
private String uniqueId;
You can still pass the value of object1 by creating a object of TableClass and assign the String value of Object1 in it.
This works 100%. I have tested this with Postgres and Oracle database.
Label's aren't form elements. They don't have a value
. They have innerHTML
and textContent
.
Thus,
$('#telefon').html()
// or
$('#telefon').text()
or
var telefon = document.getElementById('telefon');
telefon.innerHTML;
If you are starting with your form element, check out the labels
list of it. That is,
var el = $('#myformelement');
var label = $( el.prop('labels') );
// label.html();
// el.val();
// blah blah blah you get the idea
I am using Laravel 5.4 and unfortunately although the accepted answer seems fine, for preflighted requests (like PUT
and DELETE
) which will be preceded by an OPTIONS
request, specifying the middleware in the $routeMiddleware
array (and using that in the routes definition file) will not work unless you define a route handler for OPTIONS
as well. This is because without an OPTIONS
route Laravel will internally respond to that method without the CORS headers.
So in short either define the middleware in the $middleware
array which runs globally for all requests or if you're doing it in $middlewareGroups
or $routeMiddleware
then also define a route handler for OPTIONS
. This can be done like this:
Route::match(['options', 'put'], '/route', function () {
// This will work with the middleware shown in the accepted answer
})->middleware('cors');
I also wrote a middleware for the same purpose which looks similar but is larger in size as it tries to be more configurable and handles a bunch of conditions as well:
<?php
namespace App\Http\Middleware;
use Closure;
class Cors
{
private static $allowedOriginsWhitelist = [
'http://localhost:8000'
];
// All the headers must be a string
private static $allowedOrigin = '*';
private static $allowedMethods = 'OPTIONS, GET, POST, PUT, PATCH, DELETE';
private static $allowCredentials = 'true';
private static $allowedHeaders = '';
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if (! $this->isCorsRequest($request))
{
return $next($request);
}
static::$allowedOrigin = $this->resolveAllowedOrigin($request);
static::$allowedHeaders = $this->resolveAllowedHeaders($request);
$headers = [
'Access-Control-Allow-Origin' => static::$allowedOrigin,
'Access-Control-Allow-Methods' => static::$allowedMethods,
'Access-Control-Allow-Headers' => static::$allowedHeaders,
'Access-Control-Allow-Credentials' => static::$allowCredentials,
];
// For preflighted requests
if ($request->getMethod() === 'OPTIONS')
{
return response('', 200)->withHeaders($headers);
}
$response = $next($request)->withHeaders($headers);
return $response;
}
/**
* Incoming request is a CORS request if the Origin
* header is set and Origin !== Host
*
* @param \Illuminate\Http\Request $request
*/
private function isCorsRequest($request)
{
$requestHasOrigin = $request->headers->has('Origin');
if ($requestHasOrigin)
{
$origin = $request->headers->get('Origin');
$host = $request->getSchemeAndHttpHost();
if ($origin !== $host)
{
return true;
}
}
return false;
}
/**
* Dynamic resolution of allowed origin since we can't
* pass multiple domains to the header. The appropriate
* domain is set in the Access-Control-Allow-Origin header
* only if it is present in the whitelist.
*
* @param \Illuminate\Http\Request $request
*/
private function resolveAllowedOrigin($request)
{
$allowedOrigin = static::$allowedOrigin;
// If origin is in our $allowedOriginsWhitelist
// then we send that in Access-Control-Allow-Origin
$origin = $request->headers->get('Origin');
if (in_array($origin, static::$allowedOriginsWhitelist))
{
$allowedOrigin = $origin;
}
return $allowedOrigin;
}
/**
* Take the incoming client request headers
* and return. Will be used to pass in Access-Control-Allow-Headers
*
* @param \Illuminate\Http\Request $request
*/
private function resolveAllowedHeaders($request)
{
$allowedHeaders = $request->headers->get('Access-Control-Request-Headers');
return $allowedHeaders;
}
}
Also written a blog post on this.
You can do this easily by adding a Timer to your form (from the designer) and setting it's Tick-function to run your isonline-function.
You can use a combination of Vuex actions, getters, computed properties and watchers to listen to changes on a Vuex state value.
HTML Code:
<div id="app" :style='style'>
<input v-model='computedColor' type="text" placeholder='Background Color'>
</div>
JavaScript Code:
'use strict'
Vue.use(Vuex)
const { mapGetters, mapActions, Store } = Vuex
new Vue({
el: '#app',
store: new Store({
state: {
color: 'red'
},
getters: {
color({color}) {
return color
}
},
mutations: {
setColor(state, payload) {
state.color = payload
}
},
actions: {
setColor({commit}, payload) {
commit('setColor', payload)
}
}
}),
methods: {
...mapGetters([
'color'
]),
...mapActions([
'setColor'
])
},
computed: {
computedColor: {
set(value) {
this.setColor(value)
},
get() {
return this.color()
}
},
style() {
return `background-color: ${this.computedColor};`
}
},
watch: {
computedColor() {
console.log(`Watcher in use @${new Date().getTime()}`)
}
}
})
grep -v
or
grep --invert-match
You can also do the same thing using find
:
find . -type f \( -iname "*" ! -iname ".exe" ! -iname ".html"\)
More info here.
i was facing lot of issues when i was trying other solution...... After lot of R&D now i got solution
create custom_spinner.xml in layout folder and paste this code
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorGray">
<TextView
android:id="@+id/tv_spinnervalue"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@color/colorWhite"
android:gravity="center"
android:layout_alignParentLeft="true"
android:textSize="@dimen/_18dp"
android:layout_marginTop="@dimen/_3dp"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:background="@drawable/men_icon"/>
</RelativeLayout>
in your activity
Spinner spinner =(Spinner)view.findViewById(R.id.sp_colorpalates);
String[] years = {"1996","1997","1998","1998"};
spinner.setAdapter(new SpinnerAdapter(this, R.layout.custom_spinner, years));
create a new class of adapter
public class SpinnerAdapter extends ArrayAdapter<String> {
private String[] objects;
public SpinnerAdapter(Context context, int textViewResourceId, String[] objects) {
super(context, textViewResourceId, objects);
this.objects=objects;
}
@Override
public View getDropDownView(int position, View convertView, @NonNull ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
@NonNull
@Override
public View getView(int position, View convertView, @NonNull ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
private View getCustomView(final int position, View convertView, ViewGroup parent) {
View row = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_spinner, parent, false);
final TextView label=(TextView)row.findViewById(R.id.tv_spinnervalue);
label.setText(objects[position]);
return row;
}
}
You simply have to set the state
of the your button self.x
to normal
:
self.x['state'] = 'normal'
or
self.x.config(state="normal")
This code would go in the callback for the event that will cause the Button to be enabled.
Also, the right code should be:
self.x = Button(self.dialog, text="Download", state=DISABLED, command=self.download)
self.x.pack(side=LEFT)
The method pack
in Button(...).pack()
returns None
, and you are assigning it to self.x
. You actually want to assign the return value of Button(...)
to self.x
, and then, in the following line, use self.x.pack()
.
It can be done in bash itself if you have control of the configuration file format. You just need to source (".") the configuration file rather than subshell it. That ensures the variables are created in the context of the current shell (and continue to exist) rather than the subshell (where the variable disappear when the subshell exits).
$ cat config.data
export parm_jdbc=jdbc:db2://box7.co.uk:5000/INSTA
export parm_user=pax
export parm_pwd=never_you_mind
$ cat go.bash
. config.data
echo "JDBC string is " $parm_jdbc
echo "Username is " $parm_user
echo "Password is " $parm_pwd
$ bash go.bash
JDBC string is jdbc:db2://box7.co.uk:5000/INSTA
Username is pax
Password is never_you_mind
If your config file cannot be a shell script, you can just 'compile' it before executing thus (the compilation depends on your input format).
$ cat config.data
parm_jdbc=jdbc:db2://box7.co.uk:5000/INSTA # JDBC URL
parm_user=pax # user name
parm_pwd=never_you_mind # password
$ cat go.bash
cat config.data
| sed 's/#.*$//'
| sed 's/[ \t]*$//'
| sed 's/^[ \t]*//'
| grep -v '^$'
| sed 's/^/export '
>config.data-compiled
. config.data-compiled
echo "JDBC string is " $parm_jdbc
echo "Username is " $parm_user
echo "Password is " $parm_pwd
$ bash go.bash
JDBC string is jdbc:db2://box7.co.uk:5000/INSTA
Username is pax
Password is never_you_mind
In your specific case, you could use something like:
$ cat config.data
export p_p1=val1
export p_p2=val2
$ cat go.bash
. ./config.data
echo "select * from dbtable where p1 = '$p_p1' and p2 like '$p_p2%' order by p1"
$ bash go.bash
select * from dbtable where p1 = 'val1' and p2 like 'val2%' order by p1
Then pipe the output of go.bash into MySQL and voila, hopefully you won't destroy your database :-).
I think it's a little simpler to use the dplyr
functions select
and left_join
; at least it's easier for me to understand. The join function from dplyr
are made to mimic sql arguments.
library(tidyverse)
DF2 <- DF2 %>%
select(client, LO)
joined_data <- left_join(DF1, DF2, by = "Client")
You don't actually need to use the "by" argument in this case because the columns have the same name.
"[a-z]y
: Copy text to the [a-z] register
Use :!
to go to the edit command
Ctrl + R: Follow the register identity to paste what you copy.
It used to CentOS 7.
its very simple , - GOTO command line (Window + R [type cmd]) - type ipconfig , that will show the current IP address of your PC - write taht IP address on your Android Phone's browser with :80 e.g (http://192.168.x.x:80)
Done
localhost will appear on your Phone
This can be resolved in resolved with the following steps :
1. $ php artisan cache:clear
2. $ sudo chmod -R 777 storage
3. $ composer dump-autoload
Hope it helps
You can try this:
td p {word-break:break-all;}
This, however, makes it appear like this when there's enough space, unless you add a <br>
tag:
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
So, I would then suggest adding <br>
tags where there are newlines, if possible.
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
Also, if this doesn't solve your problem, there's a similar thread here.
Try these styles:
p.event_desc {_x000D_
font: bold 12px "Helvetica Neue", Helvetica, Arial, sans-serif;_x000D_
line-height: 14px;_x000D_
height:75px;_x000D_
margin: 0px;_x000D_
display: table-cell;_x000D_
vertical-align: middle;_x000D_
padding: 10px;_x000D_
border: 1px solid #f00;_x000D_
}
_x000D_
<p class="event_desc">lorem ipsum</p>
_x000D_
Simplifying Damian's great answer,
public static T ParseXml<T>(this string value) where T : class
{
var xmlSerializer = new XmlSerializer(typeof(T));
using (var textReader = new StringReader(value))
{
return (T) xmlSerializer.Deserialize(textReader);
}
}
If you are working in asp.net with razor, and you want to control multiple submit button event.then this answer will guide you. Lets for example we have two button, one button will redirect us to "PageA.cshtml" and other will redirect us to "PageB.cshtml".
@{
if (IsPost)
{
if(Request["btn"].Equals("button_A"))
{
Response.Redirect("PageA.cshtml");
}
if(Request["btn"].Equals("button_B"))
{
Response.Redirect("PageB.cshtml");
}
}
}
<form method="post">
<input type="submit" value="button_A" name="btn"/>;
<input type="submit" value="button_B" name="btn"/>;
</form>
patterns module is not supported.. mine worked with this.
from django.conf.urls import *
from django.contrib import admin
admin.autodiscover()
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
# ... your url patterns
]
Just wanted to contribute a solution that I used for my app.
It is also based on the OnScrollListener
interface, but I found it to have a much better scrolling performance on low-end devices, since none of the visible/total count calculations are carried out during the scroll operations.
ListFragment
or ListActivity
implement OnScrollListener
Add the following methods to that class:
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
//leave this empty
}
@Override
public void onScrollStateChanged(AbsListView listView, int scrollState) {
if (scrollState == SCROLL_STATE_IDLE) {
if (listView.getLastVisiblePosition() >= listView.getCount() - 1 - threshold) {
currentPage++;
//load more list items:
loadElements(currentPage);
}
}
}
where currentPage
is the page of your datasource that should be added to your list, and threshold
is the number of list items (counted from the end) that should, if visible, trigger the loading process. If you set threshold
to 0
, for instance, the user has to scroll to the very end of the list in order to load more items.
(optional) As you can see, the "load-more check" is only called when the user stops scrolling. To improve usability, you may inflate and add a loading indicator to the end of the list via listView.addFooterView(yourFooterView)
. One example for such a footer view:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/footer_layout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp" >
<ProgressBar
android:id="@+id/progressBar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_gravity="center_vertical" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="@+id/progressBar1"
android:padding="5dp"
android:text="@string/loading_text" />
</RelativeLayout>
(optional) Finally, remove that loading indicator by calling listView.removeFooterView(yourFooterView)
if there are no more items or pages.
You don't need to wrap the iframe with an additional tag. Just make sure you increase the width and height of the iframe by the same amount you scale down the iframe.
e.g. to scale the iframe content to 80% :
#frame { /* Example size! */
height: 400px; /* original height */
width: 100%; /* original width */
}
#frame {
height: 500px; /* new height (400 * (1/0.8) ) */
width: 125%; /* new width (100 * (1/0.8) )*/
transform: scale(0.8);
transform-origin: 0 0;
}
Basically, to get the same size iframe you need to scale the dimensions.
I have query,
$("#login-button").click(function(e){ alert("hiii");
var username = $("#username-field").val();
var password = $("#username-field").val();
alert(username);
alert("password" + password);
var markers = { "userName" : "admin","password" : "admin123"};
$.ajax({
type: "POST",
url: url,
// The key needs to match your method's input parameter (case-sensitive).
data: JSON.stringify(markers),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){alert("got the data"+data);},
failure: function(errMsg) {
alert(errMsg);
}
});
});
I'm posting the the login details in json and getting a string as "Success"
,but I'm not getting the response.
The above solutions suggesting the use of regex aren't ideal because this is such a small task and regex requires more resource overhead than the simplicity of the task justifies.
Here's what I do:
myString = myString.replace(' ', '').replace('\t', '').replace('\n', '')
or if you had a bunch of things to remove such that a single line solution would be gratuitously long:
removal_list = [' ', '\t', '\n']
for s in removal_list:
myString = myString.replace(s, '')
If you set your executable dir dependencies in ProjectProperties>Debugging>Environment, the paths are stored in '.user' files.
Suppose I set this string in above-mentioned field: "PATH=C:\xyz\bin" This is how it will get stored in '.user' file:
<LocalDebuggerEnvironment>PATH=C:\xyz\bin$(LocalDebuggerEnvironment)</LocalDebuggerEnvironment>
This helped us a lot while working in OpenCV. We could use different versions of OpenCV for different projects. Another advantage is, it was very easy to set up our projects on a new machine. We just had to copy corresponding dependency dirs. So for some projects, I prefer to add the '.user' to source control.
Even though, it is entirely dependent on projects. You can take a call based on your needs.
To answer Philipp's concern ( in the comments ), slicing works ok for unicode strings too
>>> greek=u"aß?de??????µ???p??st?f???"
>>> print len(greek)
25
>>> print greek[:10]
aß?de?????
If you want to run the above code as a script, put this line at the top
# -*- coding: utf-8 -*-
If your editor doesn't save in utf-8, substitute the correct encoding
To properly format numbers in columns, it's best to use printf. Depending on how big are the max or min numbers, you might want to adjust the pattern "%4d"
. For instance to allow any integer between Integer.MIN_VALUE
and Integer.MAX_VALUE
, use "%12d"
.
public void printMatrix(int[][] matrix) {
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[row].length; col++) {
System.out.printf("%4d", matrix[row][col]);
}
System.out.println();
}
}
Example output:
36 913 888 908
732 626 61 237
5 8 50 265
192 232 129 307
//file1.php
<?php
class ClassA
{
private $name = 'John';
function getName()
{
return $this->name;
}
}
?>
//file2.php
<?php
include ("file1.php");
class ClassB
{
function __construct()
{
}
function callA()
{
$classA = new ClassA();
$name = $classA->getName();
echo $name; //Prints John
}
}
$classb = new ClassB();
$classb->callA();
?>
I think you need this ..
Dim n as Integer
For n = 5 to 17
msgbox cells(n,3) '--> sched waste
msgbox cells(n,4) '--> type of treatm
msgbox format(cells(n,5),"dd/MM/yyyy") '--> Lic exp
msgbox cells(n,6) '--> email col
Next
I have just published to npm a micro-library called sort-helper (source on github). The idea is to import the helper by
to create the comparison function for sort
array method through the syntax items.sort(by(column, ...otherColumns))
, with several way to express the columns to sort by:
persons.sort(by('lastName', 'firstName'))
,dates.sort(by(x => x.toISOString()))
,[3, 2, 4, 1].sort(by(desc(n => n)))
? [3, 2, 1, 0]
,['B', 'D', 'c', 'a'].sort(by(ignoreCase(x => x))).join('')
? 'aBcD'
.It's similar to the nice thenBy mentioned in this answer but with the following differences that may be more to the taste of some:
thenBy
fluent API),I faced similar issue while restarting Nginx and found it to be a cause of SeLinux. Be sure to give a try after either disabling SeLinux or temporarily setting it to Permissive mode using below command:
setenforce 0
I hope it helps :)
Instead of getting the checked value you are setting it with:
var checked = $(this).attr('checked', true);
To properly get it:
var checked = $(this).attr('checked');
// select radio buttons group (same name)
var radioButtons = $("input[type='radio'][name='rr']");
// save initial ckecked states
var radioStates = {};
$.each(radioButtons, function(index, rd) {
radioStates[rd.value] = $(rd).is(':checked');
});
// handle click event
radioButtons.click(function() {
// check/unchek radio button
var val = $(this).val();
$(this).prop('checked', (radioStates[val] = !radioStates[val]));
// update other buttons checked state
$.each(radioButtons, function(index, rd) {
if(rd.value !== val) {
radioStates[rd.value] = false;
}
});
});
P.S.: $().attr
should be used instead of $().prop
for jquery < 1.6
Cocoa has couple of methods for this:
in NSDate
– isEqualToDate:
– earlierDate:
– laterDate:
– compare:
When you use - (NSComparisonResult)compare:(NSDate *)anotherDate
,you get back one of these:
The receiver and anotherDate are exactly equal to each other, NSOrderedSame
The receiver is later in time than anotherDate, NSOrderedDescending
The receiver is earlier in time than anotherDate, NSOrderedAscending.
example:
NSDate * now = [NSDate date];
NSDate * mile = [[NSDate alloc] initWithString:@"2001-03-24 10:45:32 +0600"];
NSComparisonResult result = [now compare:mile];
NSLog(@"%@", now);
NSLog(@"%@", mile);
switch (result)
{
case NSOrderedAscending: NSLog(@"%@ is in future from %@", mile, now); break;
case NSOrderedDescending: NSLog(@"%@ is in past from %@", mile, now); break;
case NSOrderedSame: NSLog(@"%@ is the same as %@", mile, now); break;
default: NSLog(@"erorr dates %@, %@", mile, now); break;
}
[mile release];
@NgModule({
declarations: [
SearchComponent
],
exports: [
CommonModule,
MatInputModule,
MatButtonModule,
MatCardModule,
MatFormFieldModule,
MatDialogModule,
]
})
export class MaterialModule { }
Also, do not forget to import the MaterialModule
in the imports array of AppModule
.
Your "listen" directives are wrong. See this page: http://nginx.org/en/docs/http/server_names.html.
They should be
server {
listen 80;
server_name www.domain1.com;
root /var/www/domain1;
}
server {
listen 80;
server_name www.domain2.com;
root /var/www/domain2;
}
Note, I have only included the relevant lines. Everything else looked okay but I just deleted it for clarity. To test it you might want to try serving a text file from each server first before actually serving php. That's why I left the 'root' directive in there.
rm -r ./folder -Force
...worked for me
User the below code for omit/excludes from creating setter and getter. value key should use inside @Getter
and @Setter
.
@Getter(value = AccessLevel.NONE)
@Setter(value = AccessLevel.NONE)
private int mySecret;
Spring boot 2.3 version, this is working well.
I thought I would give my full solution since there are two different ways of getting a screenshot. One is from the local browser, and one is from the remote browser. I even embed the image into the HTML report:
@After()
public void selenium_after_step(Scenario scenario) throws IOException, JSONException {
if (scenario.isFailed()){
scenario.write("Current URL = " + driver.getCurrentUrl() + "\n");
try{
driver.manage().window().maximize(); // Maximize window to get full screen for chrome
}
catch (org.openqa.selenium.WebDriverException e){
System.out.println(e.getMessage());
}
try {
if(isAlertPresent()){
Alert alert = getAlertIfPresent();
alert.accept();
}
byte[] screenshot;
if(false /*Remote Driver flow*/) { // Get a screenshot from the remote driver
Augmenter augmenter = new Augmenter();
TakesScreenshot ts = (TakesScreenshot) augmenter.augment(driver);
screenshot = ts.getScreenshotAs(OutputType.BYTES);
}
else { // Get a screenshot from the local driver
// Local webdriver user flow
screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
}
scenario.embed(screenshot, "image/png"); // Embed the image in reports
}
catch (WebDriverException wde) {
System.err.println(wde.getMessage());
}
catch (ClassCastException cce) {
cce.printStackTrace();
}
}
//seleniumCleanup();
}
ephemeral is just another name of root volume when you launch Instance from AMI backed from Amazon EC2 instance store
So Everything will be stored on ephemeral.
if you have launched your instance from AMI backed by EBS volume then your instance does not have ephemeral.
If the only characters to consider are letters then you can do:
select X from myTable where upper(X) = lower(X)
But of course that won't filter out other characters, just letters.
Follow these two steps:
Register the .net framework version version 4.0 (if it is not registered)
C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319>aspnet_regiis -i
In the app pool change the .net framework to v4.0
You can use the annotate command to place text annotations at any x and y values you want. To place them exactly at the data points you could do this
import numpy
from matplotlib import pyplot
x = numpy.arange(10)
y = numpy.array([5,3,4,2,7,5,4,6,3,2])
fig = pyplot.figure()
ax = fig.add_subplot(111)
ax.set_ylim(0,10)
pyplot.plot(x,y)
for i,j in zip(x,y):
ax.annotate(str(j),xy=(i,j))
pyplot.show()
If you want the annotations offset a little, you could change the annotate
line to something like
ax.annotate(str(j),xy=(i,j+0.5))
BufferedImage consists of two main classes: Raster & ColorModel. Raster itself consists of two classes, DataBufferByte for image content while the other for pixel color.
if you want the data from DataBufferByte, use:
public byte[] extractBytes (String ImageName) throws IOException {
// open image
File imgPath = new File(ImageName);
BufferedImage bufferedImage = ImageIO.read(imgPath);
// get DataBufferBytes from Raster
WritableRaster raster = bufferedImage .getRaster();
DataBufferByte data = (DataBufferByte) raster.getDataBuffer();
return ( data.getData() );
}
now you can process these bytes by hiding text in lsb for example, or process it the way you want.
Run command rndc querylog on
or add querylog yes;
to options{};
section in named.conf
to activate that channel.
Also make sure you’re checking correct directory if your bind is chrooted.
For two char sequence as delimeters "AND" and "OR" this should be worked. Don't forget to trim while using.
String text ="ISTANBUL AND NEW YORK AND PARIS OR TOKYO AND MOSCOW";
String[] cities = text.split("AND|OR");
Result : cities = {"ISTANBUL ", " NEW YORK ", " PARIS ", " TOKYO ", " MOSCOW"}
I know this has already been answered, but I spent some time wrestling with the second answer to get the native context menu to disappear and have it show up where the user clicked.
HTML
<body>
<div id="test1">
<a href="www.google.com" class="test">Google</a>
<a href="www.google.com" class="test">Link 2</a>
<a href="www.google.com" class="test">Link 3</a>
<a href="www.google.com" class="test">Link 4</a>
</div>
<!-- initially hidden right-click menu -->
<div class="hide" id="rmenu">
<ul>
<li class="White">White</li>
<li>Green</li>
<li>Yellow</li>
<li>Orange</li>
<li>Red</li>
<li>Blue</li>
</ul>
</div>
</body>
CSS
.hide {
display: none;
}
#rmenu {
border: 1px solid black;
background-color: white;
}
#rmenu ul {
padding: 0;
list-style: none;
}
#rmenu li
{
list-style: none;
padding-left: 5px;
padding-right: 5px;
}
JavaScript
if (document.getElementById('test1').addEventListener) {
document.getElementById('test1').addEventListener('contextmenu', function(e) {
$("#rmenu").toggleClass("hide");
$("#rmenu").css(
{
position: "absolute",
top: e.pageY,
left: e.pageX
}
);
e.preventDefault();
}, false);
}
// this is from another SO post...
$(document).bind("click", function(event) {
document.getElementById("rmenu").className = "hide";
});
None of these attributes are reliable because per the servlet spec (2.4, 2.5 and 3.0), these attributes are overridden if you include/forward a second time (or if someone calls getNamedDispatcher). I think the only reliable way to get the original request URI/query string is to stick a filter at the beginning of your filter chain in web.xml that sets your own custom request attributes based on request.getRequestURI()/getQueryString() before any forwards/includes take place.
http://www.caucho.com/resin-3.0/webapp/faq.xtp contains an excellent summary of how this works (minus the technical note that a second forward/include messes up your ability to use these attributes).
Delete the "target" folder under the offending module. Then Build | Rebuild Project. Also make sure your clear the web browsers cache.
This is answered in the documentation:
Where MySQL Stores Temporary Files
On Unix, MySQL uses the value of the TMPDIR environment variable as the path name of the directory in which to store temporary files. If TMPDIR is not set, MySQL uses the system default, which is usually /tmp, /var/tmp, or /usr/tmp.
On Windows, Netware and OS2, MySQL checks in order the values of the TMPDIR, TEMP, and TMP environment variables. For the first one found to be set, MySQL uses it and does not check those remaining. If none of TMPDIR, TEMP, or TMP are set, MySQL uses the Windows system default, which is usually C:\windows\temp.
The servlet container's implementation of HttpServlet.service()
method will automatically forward to doGet()
or doPost()
as necessary, so you shouldn't need to override the service method.
Session State may be broken if you have the following in Web.Config:
<httpModules>
<clear/>
</httpModules>
If this is the case, you may want to comment out such section, and you won't need any other changes to fix this issue.
Yes it's true but you shouldn't care. Go with the one that's easier to read. If you have to benchmark your app, then focus on the bottlenecks.
I would guess that string concatenation isn't going to be your bottleneck.
The Content-Type
header is just used as info for your application. The browser doesn't care what it is. The browser just returns you the data from the AJAX call. If you want to parse it as JSON, you need to do that on your own.
The header is there so your app can detect what data was returned and how it should handle it. You need to look at the header, and if it's application/json
then parse it as JSON.
This is actually how jQuery works. If you don't tell it what to do with the result, it uses the Content-Type
to detect what to do with it.
@foreach (var m in Model)
{
<img src="~/Images/@m.Url" style="overflow: hidden; position: relative; width:200px; height:200px;" />
}
$('#yourdropddownid').val('fg');
Optionally,
$('select>option:eq(3)').attr('selected', true);
where 3
is the index of the option you want.
As mentioned, one way is to use
new Integer(my_int_value)
But you should not call the constructor for wrapper classes directly
So, modify the code accordingly:
mBitmapCache.put(Integer.valueOf(R.drawable.bg1),object);
Use fresco. Here's how to do it:
http://frescolib.org/docs/animations.html
Here's the repo with the sample:
https://github.com/facebook/fresco/tree/master/samples/animation
Beware fresco does not support wrap content!
Adding to the above. You use the Dispatch timer if you want the tick events marshalled back to the UI thread. Otherwise I would use System.Timers.Timer.
It should also be mentioned that the "pk" should be a key field. The self-join
SELECT t1.* FROM db.table t1
JOIN db.table t2 ON t1.someField = t2.someField AND t1.pk != t2.pk
by Bill Karwin give you all the records that are duplicates which is what I wanted. Because some have more than two, you can get the same record more than once. I wrote all to another table with the same fields to get rid of the same records by key fields suppression. I tried
SELECT * FROM db.table HAVING COUNT(someField) > 1
above first. The data returned from it give only one of the duplicates, less than 1/2 of what this gives you but the count is good if that is all you want.
<input type="checkbox" id="something" />
$("#something").click( function(){
if( $(this).is(':checked') ) alert("checked");
});
Edit: Doing this will not catch when the checkbox changes for other reasons than a click, like using the keyboard. To avoid this problem, listen to change
instead of click
.
For checking/unchecking programmatically, take a look at Why isn't my checkbox change event triggered?
I needed a way to repeat/loop an array (with n items) m times.
For example, distributing a list (of persons) to a week/month. Let's say I have 3 names, and I want to them to repeat in a week:
fillArray(["Adam", "Blair", "Curtis"], 7); // returns ["Adam", "Blair", "Curtis", "Adam", "Blair", "Curtis", "Adam"]
function fillArray(pattern, count) {
let result = [];
if (["number", "string"].includes(typeof pattern)) {
result = new Array(5);
result.fill(pattern);
}
else if (pattern instanceof Array) {
for (let i = 0; i < count; i++) {
result = result.concat(pattern);
}
result = result.slice(0, count);
}
return result;
}
fillArray("a", 5); // ["a", "a", "a", "a", "a"]
fillArray(1, 5); // [1, 1, 1, 1, 1]
fillArray(["a", "b"], 5); // ["a", "b", "a", "b", "a"]
0 * * * * cd folder_containing_exe && ./exe_name
should work unless there is something else that needs to be setup for the program to run.
In my case I needed the keyboard to stay hidden and just after the click of the button my layout needs to be adjusted, so I just added this command in the manifest and it got super right.
android:windowSoftInputMode="stateHidden|adjustResize"
Creating a .bashrc file in your home directory also works. That way you don't have to copy your .bash_profile every time you install a new version of git bash.
From Android Support Library v26 + Android Studio 3.0 onwards, this process has become easy as a flick!!
Follow these steps to change the font of Toolbar Title:
res > font
as per Fonts in XMLIn res > values > styles
, paste the following (use your imagination here!)
<style name="TitleBarTextAppearance" parent="android:TextAppearance">
<item name="android:fontFamily">@font/your_desired_font</item>
<item name="android:textSize">23sp</item>
<item name="android:textStyle">bold</item>
<item name="android:textColor">@android:color/white</item>
</style>
Insert a new line in your Toolbar properties app:titleTextAppearance="@style/TextAppearance.TabsFont"
as shown below
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:titleTextAppearance="@style/TitleBarTextAppearance"
app:popupTheme="@style/AppTheme.PopupOverlay"/>
Enjoy Custom Actionbar Title font styling!!
Is it a corporate Windows machine? If so aggressive virus scanners can really slow down modern IDEs. Check your task manager for processes that are using a lot of CPU or disk reads.
This does it. Note that with an odd number of elements the one in the middle won't be included.
test = [1, 23, 4, 6, 7, 8, 5]
for i in range(len(test)/2):
print (test[i], test[-1-i])
Output:
(1, 5)
(23, 8)
(4, 7)
What worked for me now is:
CSS:
.right {
text-align: right;
margin-right: 1em;
}
.left {
text-align: left;
margin-left: 1em;
}
HTML:
<table width="100%">
<tbody>
<tr>
<td class="left">
<input id="abort" type="submit" name="abort" value="Back">
<input id="save" type="submit" name="save" value="Save">
</td>
<td class="right">
<input id="delegate" type="submit" name="delegate" value="Delegate">
<input id="unassign" type="submit" name="unassign" value="Unassign">
<input id="complete" type="submit" name="complete" value="Complete">
</td>
</tr>
</tbody>
</table>
See the following fiddle:
Here is an interesting solution: it uses the browsers CSS engine to to add a dummy property to elements matching the selector and then evaluates the computed style to find matched elements:
It does dynamically create a style rule [...] It then scans the whole document (using the much decried and IE-specific but very fast document.all) and gets the computed style for each of the elements. We then look for the foo property on the resulting object and check whether it evaluates as “bar”. For each element that matches, we add to an array.
rapidjson is a C++ JSON parser/generator designed to be fast and small memory footprint.
There is a performance comparison with YAJL and JsonCPP.
Update:
I created an open source project Native JSON benchmark, which evaluates 29 (and increasing) C/C++ JSON libraries, in terms of conformance and performance. This should be an useful reference.
How about
sub foo()
dim r As Range, rows As Long, i As Long
Set r = ActiveSheet.Range("A1:Z50")
rows = r.rows.Count
For i = rows To 1 Step (-1)
If WorksheetFunction.CountA(r.rows(i)) = 0 Then r.rows(i).Delete
Next
End Sub
Try this
Option Explicit
Sub Sample()
Dim i As Long
Dim DelRange As Range
On Error GoTo Whoa
Application.ScreenUpdating = False
For i = 1 To 50
If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
If DelRange Is Nothing Then
Set DelRange = Range("A" & i & ":" & "Z" & i)
Else
Set DelRange = Union(DelRange, Range("A" & i & ":" & "Z" & i))
End If
End If
Next i
If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
Application.ScreenUpdating = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume LetsContinue
End Sub
IF you want to delete the entire row then use this code
Option Explicit
Sub Sample()
Dim i As Long
Dim DelRange As Range
On Error GoTo Whoa
Application.ScreenUpdating = False
For i = 1 To 50
If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
If DelRange Is Nothing Then
Set DelRange = Rows(i)
Else
Set DelRange = Union(DelRange, Rows(i))
End If
End If
Next i
If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
Application.ScreenUpdating = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume LetsContinue
End Sub
I feel the simplest way would be
from matplotlib import pyplot;
from pylab import genfromtxt;
mat0 = genfromtxt("data0.txt");
mat1 = genfromtxt("data1.txt");
pyplot.plot(mat0[:,0], mat0[:,1], label = "data0");
pyplot.plot(mat1[:,0], mat1[:,1], label = "data1");
pyplot.legend();
pyplot.show();
I would say that you have a problem connecting from PHP to MySQL...
Something like PHP trying to find some socket file, and not finding it, maybe ?
(I've had this problem a couple of times -- not sure the error I got was exactly this one, though)
If you are running some Linux-based system, there should be a my.cnf
file somewhere, that is used to configure MySQL -- on my Ubuntu, it's in /etc/mysql/
.
In this file, there might be something like this :
socket = /var/run/mysqld/mysqld.sock
PHP need to use the same file -- and, depending on your distribution, the default file might not be the same as the one that MySQL uses.
In this case, adding these lines to your php.ini
file might help :
mysql.default_socket = /var/run/mysqld/mysqld.sock
mysqli.default_socket = /var/run/mysqld/mysqld.sock
pdo_mysql.default_socket = /var/run/mysqld/mysqld.sock
(You'll need to restart Apache so the modification to php.ini
is taken into account)
The last one should be enough for PDO, which is used by Zend Framework -- but the two previous ones will not do any harm, and can be useful for other applications.
If this doesn't help : can you connect to your database using PDO, in another script, that's totally independant of Zend Framework ?
i.e. does something like this work (quoting) :
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
If no, the problem is definitly not with ZF, and is a configuration / installation problem of PHP.
If yes... Well, it means you have a problem with ZF, and you'll need to give us more informations about your setup (like your DSN, for instance ? )
When specifying your cron values you'll need to make sure that your values fall within the ranges. For instance, some cron's use a 0-7 range for the day of week where both 0 and 7 represent Sunday. We do not(check below).
Seconds: 0-59
Minutes: 0-59
Hours: 0-23
Day of Month: 1-31
Months: 0-11
Day of Week: 0-6
reference: https://github.com/ncb000gt/node-cron
Use strncpy
e.g.
strncpy(dest, src + beginIndex, endIndex - beginIndex);
This assumes you've
dest
is large enough.endIndex
is greater than beginIndex
beginIndex
is less than strlen(src)
endIndex
is less than strlen(src)
When you #include
a header, it's exactly as if you put the code into the source file itself. In both cases the varGlobal
variable is defined in the source so it will work no matter how it's declared.
Also as pointed out in the comments, C++ variables at file scope are not static in scope even though they will be assigned to static storage. If the variable were a class member for example, it would need to be accessible to other compilation units in the program by default and non-class members are no different.
If you just want the response as text and don't want to convert it into JSON, use https://developer.mozilla.org/en-US/docs/Web/API/Body/text and then then
it to get the actual result of the promise:
fetch('city-market.md')
.then(function(response) {
response.text().then((s) => console.log(s));
});
or
fetch('city-market.md')
.then(function(response) {
return response.text();
})
.then(function(myText) {
console.log(myText);
});
Add this function to your application and simply call.
function getQuery($sql){
$query = str_replace(array('?'), array('\'%s\''), $sql->toSql());
$query = vsprintf($query, $sql->getBindings());
return $query;
}
Output: "select * from user
where lang
= 'en' and status
= '1' order by updated_at
desc limit 25 offset 0"
You were almost right, there's just need one little fix to be made:
var a = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)
.AddMilliseconds(1310522400000)
.ToLocalTime();
I ended up fixing our Ubuntu 18.04 / Apache 2.4.29 / PHP 7.2 install for Chrome 80 by installing mod_headers:
a2enmod headers
Adding the following directive to our Apache VirtualHost configurations:
Header edit Set-Cookie ^(.*)$ "$1; Secure; SameSite=None"
And restarting Apache:
service apache2 restart
In reviewing the docs (http://www.balkangreenfoundation.org/manual/en/mod/mod_headers.html) I noticed the "always" condition has certain situations where it does not work from the same pool of response headers. Thus not using "always" is what worked for me with PHP but the docs suggest that if you want to cover all your bases you could add the directive both with and without "always". I have not tested that.
I have an Xml File books.xml
<ParameterDBConfig>
<ID Definition="1" />
</ParameterDBConfig>
Program:
XmlDocument doc = new XmlDocument();
doc.Load("D:/siva/books.xml");
XmlNodeList elemList = doc.GetElementsByTagName("ID");
for (int i = 0; i < elemList.Count; i++)
{
string attrVal = elemList[i].Attributes["Definition"].Value;
}
Now, attrVal
has the value of ID
.
(WHEN .wsdl is referring to .xsd/schemas using import) If you're using the WMB Tooklit (v8.0.0.4 WMB) then you can find .xsd using following steps :
Create library (optional) > Right Click , New Message Model File > Select SOAP XML > Choose Option 'I already have WSDL for my data' > 'Select file outside workspace' > 'Select the WSDL bindings to Import' (if there are multiple) > Finish.
This will give you the .xsd and .wsdl files in your Workspace (Application Perspective).
#include <time.h>
clock_t uptime = clock() / (CLOCKS_PER_SEC / 1000);
The best method is what Mark Byers explains:
s = s.substring(0, s.length() - 1)
For example, if we want to replace \ to space " " with ReplaceAll, it doesn't work fine
String.replaceAll("\\", "");
or
String.replaceAll("\\$", ""); //if it is a path
If you are using Rails there's also remove
.
E.g. "Testmessage".remove("message")
yields "Test"
.
Warning: this method removes all occurrences
Below is a long polling solution I have developed for Inform8 Web. Basically you override the class and implement the loadData method. When the loadData returns a value or the operation times out it will print the result and return.
If the processing of your script may take longer than 30 seconds you may need to alter the set_time_limit() call to something longer.
Apache 2.0 license. Latest version on github https://github.com/ryanhend/Inform8/blob/master/Inform8-web/src/config/lib/Inform8/longpoll/LongPoller.php
Ryan
abstract class LongPoller {
protected $sleepTime = 5;
protected $timeoutTime = 30;
function __construct() {
}
function setTimeout($timeout) {
$this->timeoutTime = $timeout;
}
function setSleep($sleep) {
$this->sleepTime = $sleepTime;
}
public function run() {
$data = NULL;
$timeout = 0;
set_time_limit($this->timeoutTime + $this->sleepTime + 15);
//Query database for data
while($data == NULL && $timeout < $this->timeoutTime) {
$data = $this->loadData();
if($data == NULL){
//No new orders, flush to notify php still alive
flush();
//Wait for new Messages
sleep($this->sleepTime);
$timeout += $this->sleepTime;
}else{
echo $data;
flush();
}
}
}
protected abstract function loadData();
}
Think about it this way: you access static members via type name, like this:
MyStaticType.MyStaticMember();
Were you to inherit from that class, you would have to access it via the new type name:
MyNewType.MyStaticMember();
Thus, the new item bears no relationships to the original when used in code. There would be no way to take advantage of any inheritance relationship for things like polymorphism.
Perhaps you're thinking you just want to extend some of the items in the original class. In that case, there's nothing preventing you from just using a member of the original in an entirely new type.
Perhaps you want to add methods to an existing static type. You can do that already via extension methods.
Perhaps you want to be able to pass a static Type
to a function at runtime and call a method on that type, without knowing exactly what the method does. In that case, you can use an Interface.
So, in the end you don't really gain anything from inheriting static classes.
If all you need is the classpath entries, I do something like the following to use the eclipse build path.
<xmlproperty file=".classpath" collapseAttributes="true" delimiter=";" />
Then set that value in the path
<path id="eclipse.classpath">
<pathelement path="${classpath.classpathentry.path}"/>
</path>
<target name="compile" depends="init">
<javac srcdir="${src}" destdir="${build}" updatedProperty="compiled">
<classpath refid="eclipse.classpath"/>
</javac>
</target>
If anyone is looking for an updated correct syntax for this as I was, try the following:
Example:
dg.Rows[0].Cells[6].Value = "test";
It seems to be a python bug (that works perfectly in vim).
The source of the problem is the (\s*...)+ bit. Basically , you can't do (\s*)+
which make sense , because you are trying to repeat something which can be null.
>>> re.compile(r"(\s*)+")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/re.py", line 180, in compile
return _compile(pattern, flags)
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/re.py", line 233, in _compile
raise error, v # invalid expression
sre_constants.error: nothing to repeat
However (\s*\1)
should not be null, but we know it only because we know what's in \1. Apparently python doesn't ... that's weird.
As described in this article,
Abstract classes versus interfaces in Java 8
After introducing Default Method, it seems that interfaces and abstract classes are same. However, they are still different concept in Java 8.
Abstract class can define constructor. They are more structured and can have a state associated with them. While in contrast, default method can be implemented only in the terms of invoking other interface methods, with no reference to a particular implementation's state. Hence, both use for different purposes and choosing between two really depends on the scenario context.
Given your specs, I'd use slice-assignment:
>>> L = ['title', 'email', 'password2', 'password1', 'first_name', 'last_name', 'next', 'newsletter']
>>> i = L.index('password2')
>>> L[i:i+2] = L[i+1:i-1:-1]
>>> L
['title', 'email', 'password1', 'password2', 'first_name', 'last_name', 'next', 'newsletter']
The right-hand side of the slice assignment is a "reversed slice" and could also be spelled:
L[i:i+2] = reversed(L[i:i+2])
if you find that more readable, as many would.
If you are using tortoise git you can right-click on a file and git a diff by: Right-clicking on the first file and through the tortoisegit submenu select "Diff later" Then on the second file you can also right-click on this, go to the tortoisegit submenu and then select "Diff with yourfilenamehere.txt"
Another report here: It didn't work as I exported:
export default compose(
injectIntl,
connect(mapStateToProps)(Onboarding)
);
instead of
export default compose(
injectIntl,
connect(mapStateToProps)
)(Onboarding);
Note the position of the brackets. Both are correct and won't get caught by either a linter or prettier or something similar. Took me a while to track it down.
Environ()
gets you the value of any environment variable. These can be found by doing the following command in the Command Prompt:
set
If you wanted to get the username, you would do:
Environ("username")
If you wanted to get the fully qualified name, you would do:
Environ("userdomain") & "\" & Environ("username")
1 cent: no space b/w CAST and (expression). i.e., CAST(columnName AS SIGNED).
You could set an interval that runs every 500 ms or so, along the lines of the following:
var curOffset, oldOffset;
oldOffset = $(window).scrollTop();
var $el = $('.slides_layover'); // cache jquery ref
setInterval(function() {
curOffset = $(window).scrollTop();
if(curOffset != oldOffset) {
// they're scrolling, remove your class here if it exists
if($el.hasClass('showing_layover')) $el.removeClass('showing_layover');
} else {
// they've stopped, add the class if it doesn't exist
if(!$el.hasClass('showing_layover')) $el.addClass('showing_layover');
}
oldOffset = curOffset;
}, 500);
I haven't tested this code, but the principle should work.
The syntax to statically initialize an array uses curly braces, like this:
int array[10] = { 0 };
This will zero-initialize the array.
For multi-dimensional arrays, you need nested curly braces, like this:
int cipher[Array_size][Array_size]= { { 0 } };
Note that Array_size
must be a compile-time constant for this to work. If Array_size
is not known at compile-time, you must use dynamic initialization. (Preferably, an std::vector
).
For super correctness, you should use:
Rails.root.join('foo','bar')
which will allow your app to work on platforms where /
is not the directory separator, should anyone try and run it on one.
this worked for me
sudo letsencrypt certonly -a webroot --webroot-path=/var/www/html -d
domain.com -d www.domain.com
You'll find the answer to your question in the help page for ?axis
.
Here is one of the help page examples, modified with your data:
Option 1: use xaxp
to define the axis labels
plot(x,y, xaxt="n")
axis(1, xaxp=c(10, 200, 19), las=2)
Option 2: Use at
and seq()
to define the labels:
plot(x,y, xaxt="n")
axis(1, at = seq(10, 200, by = 10), las=2)
Both these options yield the same graphic:
PS. Since you have a large number of labels, you'll have to use additional arguments to get the text to fit in the plot. I use las
to rotate the labels.
java -DLOG_DIR=${LOG_DIR} -jar myjar.jar "param1" "param2"
==> in cmd line if you have "value="${LOG_DIR}/log/clientProject/project-error.log" in xml
The most basic draggable code would be :
Element.prototype.drag = function(){
var mousemove = function(e){ // document mousemove
this.style.left = ( e.clientX - this.dragStartX ) + 'px';
this.style.top = ( e.clientY - this.dragStartY ) + 'px';
}.bind(this);
var mouseup = function(e){ // document mouseup
document.removeEventListener('mousemove',mousemove);
document.removeEventListener('mouseup',mouseup);
}.bind(this);
this.addEventListener('mousedown',function(e){ // element mousedown
this.dragStartX = e.offsetX;
this.dragStartY = e.offsetY;
document.addEventListener('mousemove',mousemove);
document.addEventListener('mouseup',mouseup);
}.bind(this));
this.style.position = 'absolute' // fixed might work as well
}
and then usage (non-jquery) :
document.querySelector('.target').drag();
or in jquery :
$('.target')[0].drag();
Notice : the dragged element should have a position:absolute
or position:fixed
applied to it for the left,top movement to work...
the codepen below has some more "advanced" features : dragStart, dragStop callbacks, css classes appending to remove text selection of other elements while dragging, and a drop feature also...
checkout the following codepen :
http://codepen.io/anon/pen/VPPaEK
its basically setting a 'mousedown' event on the element which needs to be dragged, and then binding and unbinding the document mousemove to handle the movement.
in order to set a draggable handle for the element
Element.prototype.drag = function( setup ){
var setup = setup || {};
var mousemove = function(e){ // document mousemove
this.style.left = ( e.clientX - this.dragStartX ) + 'px';
this.style.top = ( e.clientY - this.dragStartY ) + 'px';
}.bind(this);
var mouseup = function(e){ // document mouseup
document.removeEventListener('mousemove',mousemove);
document.removeEventListener('mouseup',mouseup);
}.bind(this);
var handle = setup.handle || this;
handle.addEventListener('mousedown',function(e){ // element mousedown
this.dragStartX = e.offsetX;
this.dragStartY = e.offsetY;
document.addEventListener('mousemove',mousemove);
document.addEventListener('mouseup',mouseup);
handle.classList.add('dragging');
}.bind(this));
handle.classList.add('draggable');
this.style.position = 'absolute' // fixed might work as well
}
The above code is used like so :
var setup = {
handle : document.querySelector('.handle')
};
document.querySelector('.box').drag(setup);
The problem now, is that when dragging, the text within the draggable element is annoyingly being selected with no use...
This is why we have added the draggable
and dragging
classes to the element. which will cancel out this unwanted behavior, and also add a move cursor, to display that this element is draggable
.draggable{
cursor: move;
position: fixed;
}
.draggable.dragging{
user-select: none;
}
So now that we have our draggable element, we sometimes need to call various events.
setup.ondraginit // this is called when setting up the draggable
setup.ondragstart // this is called when mouse is down on the element
setup.ondragend // this is called when mouse is released (after dragging)
setup.ondrag // this is called while the element is being dragged
Each will pass the original mouse event to the specific handler
Finally, this is what we get...
Element.prototype.drag = function( setup ){
var setup = setup || {};
var mousemove = function(e){ // document mousemove
this.style.left = ( e.clientX - this.dragStartX ) + 'px';
this.style.top = ( e.clientY - this.dragStartY ) + 'px';
setup.ondrag && setup.ondrag(e); // ondrag event
}.bind(this);
var mouseup = function(e){ // document mouseup
document.removeEventListener('mousemove',mousemove);
document.removeEventListener('mouseup',mouseup);
handle.classList.remove('dragging');
setup.ondragend && setup.ondragend(e); // ondragend event
}.bind(this);
var handle = setup.handle || this;
handle.addEventListener('mousedown',function(e){ // element mousedown
this.dragStartX = e.offsetX;
this.dragStartY = e.offsetY;
document.addEventListener('mousemove',mousemove);
document.addEventListener('mouseup',mouseup);
handle.classList.add('dragging');
setup.ondragstart && setup.ondragstart(e); // ondragstart event
}.bind(this));
handle.classList.add('draggable');
setup.ondraginit && setup.ondraginit(e); // ondraginit event
}
And to use this :
var setup = {
handle : document.querySelector('.handle'),
ondragstart : e => { console.log('drag has started!'); },
ondrag : e => { console.log('drag!'); },
ondragend : e => { console.log('drag has ended!'); }
};
document.querySelector('.box').drag(setup);
note that e.target
is a reference back to our draggable element
The definition of SIZE_T
is found at:
https://msdn.microsoft.com/en-us/library/cc441980.aspx and https://msdn.microsoft.com/en-us/library/cc230394.aspx
Pasting here the required information:
SIZE_T
is a ULONG_PTR
representing the maximum number of bytes to which a pointer can point.
This type is declared as follows:
typedef ULONG_PTR SIZE_T;
A ULONG_PTR
is an unsigned long type used for pointer precision. It is used when casting a pointer to a long type to perform pointer arithmetic.
This type is declared as follows:
typedef unsigned __int3264 ULONG_PTR;
For Loop Solution
<?php
echo replaceFirstMatchedChar("&", "?", "/property/details&id=202&test=123#tab-6");
function replaceFirstMatchedChar($searchChar, $replaceChar, $str)
{
for ($i = 0; $i < strlen($str); $i++) {
if ($str[$i] == $searchChar) {
$str[$i] = $replaceChar;
break;
}
}
return $str;
}
Async:
fs.readFile('test.txt', 'utf8', callback);
Sync:
var content = fs.readFileSync('test.txt', 'utf8');
Have you created the DSN first in Control Panel>Administrative Tools>ODBC>System DSN. Name it same as "myDatabase" and if i is asking for locating the database/access file specify the path using browse option. Once ur DSN will be created successfully you will be easily able to access ur DB.
Get FireBug for Mozilla Firefox.
use console.log(obj);
A simple JavaScript function will do the job.
function ClearFields() {
document.getElementById("textfield1").value = "";
document.getElementById("textfield2").value = "";
}
And just have your button call it:
<button type="button" onclick="ClearFields();">Clear</button>
Converting anything to a string should either 1) allocate the resultant string or 2) pass in a char *
destination and size. Sample code below:
Both work for all int
including INT_MIN
. They provide a consistent output unlike snprintf()
which depends on the current locale.
Method 1: Returns NULL
on out-of-memory.
#define INT_DECIMAL_STRING_SIZE(int_type) ((CHAR_BIT*sizeof(int_type)-1)*10/33+3)
char *int_to_string_alloc(int x) {
int i = x;
char buf[INT_DECIMAL_STRING_SIZE(int)];
char *p = &buf[sizeof buf - 1];
*p = '\0';
if (i >= 0) {
i = -i;
}
do {
p--;
*p = (char) ('0' - i % 10);
i /= 10;
} while (i);
if (x < 0) {
p--;
*p = '-';
}
size_t len = (size_t) (&buf[sizeof buf] - p);
char *s = malloc(len);
if (s) {
memcpy(s, p, len);
}
return s;
}
Method 2: It returns NULL
if the buffer was too small.
static char *int_to_string_helper(char *dest, size_t n, int x) {
if (n == 0) {
return NULL;
}
if (x <= -10) {
dest = int_to_string_helper(dest, n - 1, x / 10);
if (dest == NULL) return NULL;
}
*dest = (char) ('0' - x % 10);
return dest + 1;
}
char *int_to_string(char *dest, size_t n, int x) {
char *p = dest;
if (n == 0) {
return NULL;
}
n--;
if (x < 0) {
if (n == 0) return NULL;
n--;
*p++ = '-';
} else {
x = -x;
}
p = int_to_string_helper(p, n, x);
if (p == NULL) return NULL;
*p = 0;
return dest;
}
[Edit] as request by @Alter Mann
(CHAR_BIT*sizeof(int_type)-1)*10/33+3
is at least the maximum number of char
needed to encode the some signed integer type as a string consisting of an optional negative sign, digits, and a null character..
The number of non-sign bits in a signed integer is no more than CHAR_BIT*sizeof(int_type)-1
. A base-10 representation of a n
-bit binary number takes up to n*log10(2) + 1
digits. 10/33
is slightly more than log10(2)
. +1 for the sign char
and +1 for the null character. Other fractions could be used like 28/93.
Method 3: If one wants to live on the edge and buffer overflow is not a concern, a simple C99 or later solution follows which handles all int
.
#include <limits.h>
#include <stdio.h>
static char *itoa_simple_helper(char *dest, int i) {
if (i <= -10) {
dest = itoa_simple_helper(dest, i/10);
}
*dest++ = '0' - i%10;
return dest;
}
char *itoa_simple(char *dest, int i) {
char *s = dest;
if (i < 0) {
*s++ = '-';
} else {
i = -i;
}
*itoa_simple_helper(s, i) = '\0';
return dest;
}
int main() {
char s[100];
puts(itoa_simple(s, 0));
puts(itoa_simple(s, 1));
puts(itoa_simple(s, -1));
puts(itoa_simple(s, 12345));
puts(itoa_simple(s, INT_MAX-1));
puts(itoa_simple(s, INT_MAX));
puts(itoa_simple(s, INT_MIN+1));
puts(itoa_simple(s, INT_MIN));
}
Sample output
0
1
-1
12345
2147483646
2147483647
-2147483647
-2147483648
If it's a small dataset (e.g. 1K records), you can simply specify size
:
curl localhost:9200/foo_index/_search?size=1000
The match all query isn't needed, as it's implicit.
If you have a medium-sized dataset, like 1M records, you may not have enough memory to load it, so you need a scroll.
A scroll is like a cursor in a DB. In Elasticsearch, it remembers where you left off and keeps the same view of the index (i.e. prevents the searcher from going away with a refresh, prevents segments from merging).
API-wise, you have to add a scroll parameter to the first request:
curl 'localhost:9200/foo_index/_search?size=100&scroll=1m&pretty'
You get back the first page and a scroll ID:
{
"_scroll_id" : "DXF1ZXJ5QW5kRmV0Y2gBAAAAAAAAADEWbmJlSmxjb2hSU0tMZk12aEx2c0EzUQ==",
"took" : 0,
...
Remember that both the scroll ID you get back and the timeout are valid for the next page. A common mistake here is to specify a very large timeout (value of scroll
), that would cover for processing the whole dataset (e.g. 1M records) instead of one page (e.g. 100 records).
To get the next page, fill in the last scroll ID and a timeout that should last until fetching the following page:
curl -XPOST -H 'Content-Type: application/json' 'localhost:9200/_search/scroll' -d '{
"scroll": "1m",
"scroll_id": "DXF1ZXJ5QW5kRmV0Y2gBAAAAAAAAADAWbmJlSmxjb2hSU0tMZk12aEx2c0EzUQ=="
}'
If you have a lot to export (e.g. 1B documents), you'll want to parallelise. This can be done via sliced scroll. Say you want to export on 10 threads. The first thread would issue a request like this:
curl -XPOST -H 'Content-Type: application/json' 'localhost:9200/test/_search?scroll=1m&size=100' -d '{
"slice": {
"id": 0,
"max": 10
}
}'
You get back the first page and a scroll ID, exactly like a normal scroll request. You'd consume it exactly like a regular scroll, except that you get 1/10th of the data.
Other threads would do the same, except that id
would be 1, 2, 3...
New awesome solution with JavaScript Destructuring:
let obj = {
"key1": "value1",
"key2": "value2",
"key3": "value3",
};
let {key1, key2, key3, key4} = obj;
// key1 = "value1"
// key2 = "value2"
// key3 = "value3"
// key4 = undefined
// Can easily use `if` here on key4
if(!key4) { console.log("key not present"); } // Key not present
Doing unions in MongoDB in a 'SQL UNION' fashion is possible using aggregations along with lookups, in a single query. Here is an example I have tested that works with MongoDB 4.0:
// Create employees data for testing the union.
db.getCollection('employees').insert({ name: "John", type: "employee", department: "sales" });
db.getCollection('employees').insert({ name: "Martha", type: "employee", department: "accounting" });
db.getCollection('employees').insert({ name: "Amy", type: "employee", department: "warehouse" });
db.getCollection('employees').insert({ name: "Mike", type: "employee", department: "warehouse" });
// Create freelancers data for testing the union.
db.getCollection('freelancers').insert({ name: "Stephany", type: "freelancer", department: "accounting" });
db.getCollection('freelancers').insert({ name: "Martin", type: "freelancer", department: "sales" });
db.getCollection('freelancers').insert({ name: "Doug", type: "freelancer", department: "warehouse" });
db.getCollection('freelancers').insert({ name: "Brenda", type: "freelancer", department: "sales" });
// Here we do a union of the employees and freelancers using a single aggregation query.
db.getCollection('freelancers').aggregate( // 1. Use any collection containing at least one document.
[
{ $limit: 1 }, // 2. Keep only one document of the collection.
{ $project: { _id: '$$REMOVE' } }, // 3. Remove everything from the document.
// 4. Lookup collections to union together.
{ $lookup: { from: 'employees', pipeline: [{ $match: { department: 'sales' } }], as: 'employees' } },
{ $lookup: { from: 'freelancers', pipeline: [{ $match: { department: 'sales' } }], as: 'freelancers' } },
// 5. Union the collections together with a projection.
{ $project: { union: { $concatArrays: ["$employees", "$freelancers"] } } },
// 6. Unwind and replace root so you end up with a result set.
{ $unwind: '$union' },
{ $replaceRoot: { newRoot: '$union' } }
]);
Here is the explanation of how it works:
Instantiate an aggregate
out of any collection of your database that has at least one document in it. If you can't guarantee any collection of your database will not be empty, you can workaround this issue by creating in your database some sort of 'dummy' collection containing a single empty document in it that will be there specifically for doing union queries.
Make the first stage of your pipeline to be { $limit: 1 }
. This will strip all the documents of the collection except the first one.
Strip all the fields of the remaining document by using a $project
stage:
{ $project: { _id: '$$REMOVE' } }
Your aggregate now contains a single, empty document. It's time to add lookups for each collection you want to union together. You may use the pipeline
field to do some specific filtering, or leave localField
and foreignField
as null to match the whole collection.
{ $lookup: { from: 'collectionToUnion1', pipeline: [...], as: 'Collection1' } },
{ $lookup: { from: 'collectionToUnion2', pipeline: [...], as: 'Collection2' } },
{ $lookup: { from: 'collectionToUnion3', pipeline: [...], as: 'Collection3' } }
You now have an aggregate containing a single document that contains 3 arrays like this:
{
Collection1: [...],
Collection2: [...],
Collection3: [...]
}
You can then merge them together into a single array using a $project
stage along with the $concatArrays
aggregation operator:
{
"$project" :
{
"Union" : { $concatArrays: ["$Collection1", "$Collection2", "$Collection3"] }
}
}
You now have an aggregate containing a single document, into which is located an array that contains your union of collections. What remains to be done is to add an $unwind
and a $replaceRoot
stage to split your array into separate documents:
{ $unwind: "$Union" },
{ $replaceRoot: { newRoot: "$Union" } }
Voilà. You now have a result set containing the collections you wanted to union together. You can then add more stages to filter it further, sort it, apply skip() and limit(). Pretty much anything you want.
If the DC is Win2k3 SP2 or above, you can use something like:
(&(objectCategory=user)(memberOf:1.2.840.113556.1.4.1941:=CN=GroupOne,OU=Security Groups,OU=Groups,DC=example,DC=com))
to get the nested group membership.
Source: https://ldapwiki.com/wiki/Active%20Directory%20Group%20Related%20Searches
This doesn't work in IE6, which may be an issue, but it'll work in IE7+ and Firefox, Safari etc. It'll align the 3rd column right and all of the subsequent columns left.
td + td + td { text-align: right; }
td + td + td + td { text-align: left; }
Paul's answer is very good and it is actually how Kafka & Zk work together from a broker point of view.
I would say that another easy option to check if a Kafka server is running is to create a simple KafkaConsumer pointing to the cluste and try some action, for example, listTopics(). If kafka server is not running, you will get a TimeoutException and then you can use a try-catch
sentence.
def validateKafkaConnection(kafkaParams : mutable.Map[String, Object]) : Unit = {
val props = new Properties()
props.put("bootstrap.servers", kafkaParams.get("bootstrap.servers").get.toString)
props.put("group.id", kafkaParams.get("group.id").get.toString)
props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer")
props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer")
val simpleConsumer = new KafkaConsumer[String, String](props)
simpleConsumer.listTopics()
}
They are access modifiers and help us implement Encapsulation (or information hiding). They tell the compiler which other classes should have access to the field or method being defined.
private
- Only the current class will have access to the field or method.
protected
- Only the current class and subclasses (and sometimes also same-package classes) of this class will have access to the field or method.
public
- Any class can refer to the field or call the method.
This assumes these keywords are used as part of a field or method declaration within a class definition.
_splitpath should do what you need. You could of course do it manually but _splitpath
handles all special cases as well.
EDIT:
As BillHoag mentioned it is recommended to use the more safe version of _splitpath
called _splitpath_s when available.
Or if you want something portable you could just do something like this
std::vector<std::string> splitpath(
const std::string& str
, const std::set<char> delimiters)
{
std::vector<std::string> result;
char const* pch = str.c_str();
char const* start = pch;
for(; *pch; ++pch)
{
if (delimiters.find(*pch) != delimiters.end())
{
if (start != pch)
{
std::string str(start, pch);
result.push_back(str);
}
else
{
result.push_back("");
}
start = pch + 1;
}
}
result.push_back(start);
return result;
}
...
std::set<char> delims{'\\'};
std::vector<std::string> path = splitpath("C:\\MyDirectory\\MyFile.bat", delims);
cout << path.back() << endl;
For UWP:
<ResourceDictionary Source="ms-appx:///##Namespace.External.Assembly##/##FOLDER##/##FILE##.xaml" />
I prefer the following, as it takes into account an inset. If there is no inset, it will still scroll to the top as the inset will be 0.
tableView.setContentOffset(CGPoint(x: 0, y: -tableView.contentInset.top), animated: true)
Basic thumb rule is: For "Nouns" use Abstract class and for "Verbs" use interface
E.g: car
is an abstract class and drive
, we can make it an interface.
None of the above solutions worked for me and I don't have admin rights on my laptop, but they eventually led me to the git tools credential storage doc :
My setup Windows 10 | git version 2.18.0.windows.1 | Clone through HTTPS link
This solution works if you use wincred as credential helper :
> git config --global credential.helper
wincred
Changing the helper to "cache" should do the trick, as it will ask you to provide your credentials again. To set it to cache, just type :
> git config --global credential.helper cache
Check your update is active:
> git config --global credential.helper
cache
You should now be able to clone / pull / fetch as before.
h1 {_x000D_
border: dashed 2px blue;_x000D_
width: 200px;_x000D_
height: 200px;_x000D_
border-radius: 100px;_x000D_
text-align: center;_x000D_
line-height: 60px;_x000D_
_x000D_
}
_x000D_
<h1> <br>hello world</h1>
_x000D_
If you just want to execute the shell command in your c program, you could use,
#include <stdlib.h>
int system(const char *command);
In your case,
system("pwd");
The issue is that there isn't an executable file called "pwd" and I'm unable to execute "echo $PWD", since echo is also a built-in command with no executable to be found.
What do you mean by this? You should be able to find the mentioned packages in /bin/
sudo find / -executable -name pwd
sudo find / -executable -name echo
After adding the column, you can always add the primary key:
ALTER TABLE goods ADD PRIMARY KEY(id)
As to why your script wasn't working, you need to specify PRIMARY KEY
, not just the word PRIMARY
:
alter table goods add column `id` int(10) unsigned primary KEY AUTO_INCREMENT;
The easiest way that I have found is to set the activity's theme in the AndroidManifest to android:theme="@android:style/Theme.Holo.Dialog"
.
Then in the activity's onCreate method, call getWindow().setBackgroundDrawable(new ColorDrawable(0));
.
In regards to the first comment: If you do this you will get an error(in Android Studio). This is in regards to it being out of the Android namespace. If you don't know how to fix this error, check the example out below. Hope this helps!
Example -Before :
<string-array name="roomSize">
<item>Small(0-4)</item>
<item>Medium(4-8)</item>
<item>Large(9+)</item>
</string-array>
Example - After:
<string-array android:name="roomSize">
<item>Small(0-4)</item>
<item>Medium(4-8)</item>
<item>Large(9+)</item>
</string-array>
Use replace
method of strings not strip
:
s = s.replace(',','')
An example:
>>> s = 'Foo, bar'
>>> s.replace(',',' ')
'Foo bar'
>>> s.replace(',','')
'Foo bar'
>>> s.strip(',') # clears the ','s at the start and end of the string which there are none
'Foo, bar'
>>> s.strip(',') == s
True
this.donorsTableAdapter.Fill(this.sbmsDataSet.donors);
You can use this code for rightclick, CTRL+C, CTRL+V, CTRL+X detect and prevent their action
$(document).bind('copy', function(e) {
alert('Copy is not allowed !!!');
e.preventDefault();
});
$(document).bind('paste', function() {
alert('Paste is not allowed !!!');
e.preventDefault();
});
$(document).bind('cut', function() {
alert('Cut is not allowed !!!');
e.preventDefault();
});
$(document).bind('contextmenu', function(e) {
alert('Right Click is not allowed !!!');
e.preventDefault();
});
You can do this with LibreOffice:
libreoffice --headless --convert-to csv $filename --outdir $outdir
For reasons not clear to me, you might need to run this with sudo. You can make LibreOffice work with sudo without requiring a password by adding this line to you sudoers file:
users ALL=(ALL) NOPASSWD: libreoffice
I'm a little late, but I have a little snippet to do this, it essentially maintains all of JScripts truthey/falsey/filthy-ness but includes "false"
as an acceptible value for false.
I prefer this method to the ones mentioned because it doesn't rely on a 3rd party to parse the code (i.e: eval/JSON.parse), which is overkill in my mind, it's short enough to not require a utility function and maintains other truthey/falsey conventions.
var value = "false";
var result = (value == "false") != Boolean(value);
// value = "true" => result = true
// value = "false" => result = false
// value = true => result = true
// value = false => result = false
// value = null => result = false
// value = [] => result = true
// etc..
Something like this might help:
SET Today=%Date:~10,4%%Date:~4,2%%Date:~7,2%
mkdir C:\Test\Backup-%Today%
move C:\Test\Log\*.* C:\Test\Backup-%Today%\
SET Today=
The important part is the first line. It takes the output of the internal DATE
value and parses it into an environmental variable named Today
, in the format CCYYMMDD
, as in '20110407`.
The %Date:~10,4%
says to extract a *substring of the Date
environmental variable 'Thu 04/07/2011' (built in - type echo %Date%
at a command prompt) starting at position 10 for 4 characters (2011
). It then concatenates another substring of Date:
starting at position 4 for 2 chars (04
), and then concats two additional characters starting at position 7 (07
).
*The substring value starting points are 0-based.
You may need to adjust these values depending on the date format in your locale, but this should give you a starting point.
I am improving my answer to add more details for saving and restoring models.
In(and after) Tensorflow version 0.11:
Save the model:
import tensorflow as tf
#Prepare to feed input, i.e. feed_dict and placeholders
w1 = tf.placeholder("float", name="w1")
w2 = tf.placeholder("float", name="w2")
b1= tf.Variable(2.0,name="bias")
feed_dict ={w1:4,w2:8}
#Define a test operation that we will restore
w3 = tf.add(w1,w2)
w4 = tf.multiply(w3,b1,name="op_to_restore")
sess = tf.Session()
sess.run(tf.global_variables_initializer())
#Create a saver object which will save all the variables
saver = tf.train.Saver()
#Run the operation by feeding input
print sess.run(w4,feed_dict)
#Prints 24 which is sum of (w1+w2)*b1
#Now, save the graph
saver.save(sess, 'my_test_model',global_step=1000)
Restore the model:
import tensorflow as tf
sess=tf.Session()
#First let's load meta graph and restore weights
saver = tf.train.import_meta_graph('my_test_model-1000.meta')
saver.restore(sess,tf.train.latest_checkpoint('./'))
# Access saved Variables directly
print(sess.run('bias:0'))
# This will print 2, which is the value of bias that we saved
# Now, let's access and create placeholders variables and
# create feed-dict to feed new data
graph = tf.get_default_graph()
w1 = graph.get_tensor_by_name("w1:0")
w2 = graph.get_tensor_by_name("w2:0")
feed_dict ={w1:13.0,w2:17.0}
#Now, access the op that you want to run.
op_to_restore = graph.get_tensor_by_name("op_to_restore:0")
print sess.run(op_to_restore,feed_dict)
#This will print 60 which is calculated
This and some more advanced use-cases have been explained very well here.
A quick complete tutorial to save and restore Tensorflow models
My case is, it doesn't work wherever I call it, no matter I path the file or not, if I open it with powershell.
but it works if I open it with cmd.
here is a lambda function which removes all characters passed as string
BiFunction<String,String,String> deleteChars = (fromString, chars) -> {
StringBuilder buf = new StringBuilder( fromString );
IntStream.range( 0, buf.length() ).forEach( i -> {
while( i < buf.length() && chars.indexOf( buf.charAt( i ) ) >= 0 )
buf.deleteCharAt( i );
} );
return( buf.toString() );
};
String str = "TextX XYto modifyZ";
deleteChars.apply( str, "XYZ" ); // –> "Text to modify"
This solution takes into acount that the resulting String – in difference to replace()
– never becomes larger than the starting String when removing characters. So it avoids the repeated allocating and copying while appending character-wise to the StringBuilder
as replace()
does.
Not to mention the pointless generation of Pattern
and Matcher
instances in replace()
that are never needed for removal.
In difference to replace()
this solution can delete several characters in one swoop.
Simply set height of the select tag
select{
height: 30px;
max-height: 30px;
}
Try with the below code it`s working for me.
public static String decrypt(String encrypted) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
byte[] key = your Key in byte array;
byte[] input = salt in byte array;
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
IvParameterSpec ivSpec = new IvParameterSpec(input);
Cipher ecipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
ecipher.init(Cipher.DECRYPT_MODE, skeySpec, ivSpec);
byte[] raw = Base64.decode(encrypted, Base64.DEFAULT);
byte[] originalBytes = ecipher.doFinal(raw);
String original = new String(originalBytes, "UTF8");
return original;
}
I'm not sure you have gotten past this yet, but I had to work on something very similar today and I got your fiddle working like you are asking, basically what I did was make another table row under it, and then used the accordion control. I tried using just collapse but could not get it working and saw an example somewhere on SO that used accordion.
Here's your updated fiddle: http://jsfiddle.net/whytheday/2Dj7Y/11/
Since I need to post code here is what each collapsible "section" should look like ->
<tr data-toggle="collapse" data-target="#demo1" class="accordion-toggle">
<td>1</td>
<td>05 May 2013</td>
<td>Credit Account</td>
<td class="text-success">$150.00</td>
<td class="text-error"></td>
<td class="text-success">$150.00</td>
</tr>
<tr>
<td colspan="6" class="hiddenRow">
<div class="accordion-body collapse" id="demo1">Demo1</div>
</td>
</tr>
The other answers only show the changed files.
git log -p DIR
is very useful, if you need the full diff of all changed files in a specific subdirectory.
Example: Show all detailed changes in a specific version range
git log -p 8a5fb..HEAD -- A B
commit 62ad8c5d
Author: Scott Tiger
Date: Mon Nov 27 14:25:29 2017 +0100
My comment
...
@@ -216,6 +216,10 @@ public class MyClass {
+ Added
- Deleted
Sample code from @polyglot solution
SQLiteCommand sql_cmd;
sql_cmd.CommandText = "select seq from sqlite_sequence where name='myTable'; ";
int newId = Convert.ToInt32( sql_cmd.ExecuteScalar( ) );
Use
git clone https://github.com/<path>/repository
or
git clone https://github.com/<path>/<master>.git
examples
git clone https://github.com/spring-projects/spring-data-graph-examples
git clone https://github.com/spring-projects/spring-data-graph-examples.git
First, you should download the suitable version for your system from here: https://pecl.php.net/package/mcrypt/1.0.3/windows
Then, you should copy php_mcrypt.dll
to ../xampp/php/ext/
and enable the extension by adding extension=mcrypt
to your xampp/php/php.ini
file.
git rev-parse
Also works for getting the current branch name using the --abbrev-ref flag like:
git rev-parse --abbrev-ref HEAD
It does work in Firefox (including 2.0.0.20
). See http://jsbin.com/akili (add /edit
to the url to edit):
<p id="one">One</p>
<a href="#" onclick="document.getElementById('one').id = 'two'; return false">Link2</a>
The first click changes the id
to "two"
, the second click errors because the element with id="one"
now can't be found!
Perhaps you have another element already with id="two"
(FYI you can't have more than one element with the same id
).
Please keep attention at this syntax:
* */6 * * *
This means 60 times (every minute) every 6 hours,
not
one time every 6 hours.
This is a long way round, but if you have not yet implemented then you can originally create your models this way. The method below describes altering an existing database.
1) Create a new model for the email providers:
$ rails g model provider name
2) This will create your model with a name string and timestamps. It also creates the migration which we need to add to the schema with:
$ rake db:migrate
3) Add a migration to add the providers ID into the Contact:
$ rails g migration AddProviderRefToContacts provider:references
4) Go over the migration file to check it look OK, and migrate that too:
$ rake db:migrate
5) Okay, now we have a provider_id, we no longer need the original email_provider string:
$ rails g migration RemoveEmailProviderFromContacts
6) Inside the migration file, add the change which will look something like:
class RemoveEmailProviderFromContacts < ActiveRecord::Migration
def change
remove_column :contacts, :email_provider
end
end
7) Once that is done, migrate the change:
$ rake db:migrate
8) Let's take this moment to update our models:
Contact: belongs_to :provider
Provider: has_many :contacts
9) Then, we set up the drop down logic in the _form.html.erb partial in the views:
<div class="field">
<%= f.label :provider %><br>
<%= f.collection_select :provider_id, Provider.all, :id, :name %>
</div>
10) Finally, we need to add the provders themselves. One way top do that would be to use the seed file:
Provider.destroy_all
gmail = Provider.create!(name: "gmail")
yahoo = Provider.create!(name: "yahoo")
msn = Provider.create!(name: "msn")
$ rake db:seed
Try the following, note that when user refreshes the page, the value is "Male" again, data should be stored on database.
<p id="pTest">Male</p>
<button>change</button>
<script>
$('button').click(function(){
$('#pTest').text('test')
})
</script>
Here's an example of a union from my own codebase (from memory and paraphrased so it may not be exact). It was used to store language elements in an interpreter I built. For example, the following code:
set a to b times 7.
consists of the following language elements:
Language elements were defines as '#define
' values thus:
#define ELEM_SYM_SET 0
#define ELEM_SYM_TO 1
#define ELEM_SYM_TIMES 2
#define ELEM_SYM_FULLSTOP 3
#define ELEM_VARIABLE 100
#define ELEM_CONSTANT 101
and the following structure was used to store each element:
typedef struct {
int typ;
union {
char *str;
int val;
}
} tElem;
then the size of each element was the size of the maximum union (4 bytes for the typ and 4 bytes for the union, though those are typical values, the actual sizes depend on the implementation).
In order to create a "set" element, you would use:
tElem e;
e.typ = ELEM_SYM_SET;
In order to create a "variable[b]" element, you would use:
tElem e;
e.typ = ELEM_VARIABLE;
e.str = strdup ("b"); // make sure you free this later
In order to create a "constant[7]" element, you would use:
tElem e;
e.typ = ELEM_CONSTANT;
e.val = 7;
and you could easily expand it to include floats (float flt
) or rationals (struct ratnl {int num; int denom;}
) and other types.
The basic premise is that the str
and val
are not contiguous in memory, they actually overlap, so it's a way of getting a different view on the same block of memory, illustrated here, where the structure is based at memory location 0x1010
and integers and pointers are both 4 bytes:
+-----------+
0x1010 | |
0x1011 | typ |
0x1012 | |
0x1013 | |
+-----+-----+
0x1014 | | |
0x1015 | str | val |
0x1016 | | |
0x1017 | | |
+-----+-----+
If it were just in a structure, it would look like this:
+-------+
0x1010 | |
0x1011 | typ |
0x1012 | |
0x1013 | |
+-------+
0x1014 | |
0x1015 | str |
0x1016 | |
0x1017 | |
+-------+
0x1018 | |
0x1019 | val |
0x101A | |
0x101B | |
+-------+
if the file containing that link tag is in the root dir of the project, then the correct path would be "css/styles.css"
ngInit
can help to initialize variables.
<div ng-app='app'>
<div ng-controller="MyController" ng-init="myVar='test'">
{{myVar}}
</div>
</div>
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.addHeaderView(yourview);
I can give a small hack, you can use T-SQL function. Try this:
SELECT ID, PARSENAME(WebsiteName, 2)
FROM dbo.YourTable .....
I would recommend handling the sending of http error codes by using the Boom package.
You don't need the double backslash when using unescaped strings:
System.Diagnostics.Process.Start("explorer.exe",@"c:\teste");
In my case, I had renamed the project and changed it's folder structure. I found that updating the RootNameSpace and AssemblyName in the .csproj file where the error was being thrown resolved the error. If you have modified paths of your project I'd recommend checking this as well.
<RootNamespace>Company.Product.WebAPI</RootNamespace>
<AssemblyName>Company.Product.WebAPI</AssemblyName>
Struggled to find this as well.
Heres a screenshot of how to do it:
Straight from the designer of Lua himself:
Our main concern with "continue" is that there are several other control structures that (in our view) are more or less as important as "continue" and may even replace it. (E.g., break with labels [as in Java] or even a more generic goto.) "continue" does not seem more special than other control-structure mechanisms, except that it is present in more languages. (Perl actually has two "continue" statements, "next" and "redo". Both are useful.)
If you already know the indices:
list1 = ['x','y','z','a','b','c','d','e','f','g']
indices = [(0, 4), (5, 9)]
print [list1[s:e+1] for s,e in indices]
Note that we're adding +1 to the end to make the range inclusive...
If you need to support more than one format you will have to pattern match your input and parse accordingly.
final DateFormat fmt;
if (dateString.endsWith("Z")) {
fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
} else {
fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
}
I'd guess you're dealing with a bug in the API you're using which has quoted the Z
timezone date pattern somewhere...
Get key values from list of dictionaries in python?
Ex:
data =
[{'obj1':[{'cpu_percentage':'15%','ram':3,'memory_percentage':'66%'}]},
{'obj2': [{'cpu_percentage':'0','ram':4,'memory_percentage':'35%'}]}]
for d in data:
for key,value in d.items():
z ={key: {'cpu_percentage': d['cpu_percentage'],'memory_percentage': d['memory_percentage']} for d in value}
print(z)
Output:
{'obj1': {'cpu_percentage': '15%', 'memory_percentage': '66%'}}
{'obj2': {'cpu_percentage': '0', 'memory_percentage': '35%'}}
You'd use the corresponding method getVisibility(). Method names prefixed with 'get' and 'set' are Java's convention for representing properties. Some language have actual language constructs for properties but Java isn't one of them. So when you see something labeled 'setX', you can be 99% certain there's a corresponding 'getX' that will tell you the value.
I have created this very straightforward function, and it works like a charm:
function ts2time($timestamp,$timezone){ /* input: 1518404518,America/Los_Angeles */
$date = new DateTime(date("d F Y H:i:s",$timestamp));
$date->setTimezone(new DateTimeZone($timezone));
$rt=$date->format('M d, Y h:i:s a'); /* output: Feb 11, 2018 7:01:58 pm */
return $rt;
}
You can simply add DISTINCT in front.
SELECT GROUP_CONCAT(DISTINCT categories SEPARATOR ' ')
if you want to sort,
SELECT GROUP_CONCAT(DISTINCT categories ORDER BY categories ASC SEPARATOR ' ')
Here is an example that takes a user's input and checks if the input is a palindrome:
name = input("Write your word here: ")
input("Press <enter> to check if the word is a palindrome.")
if str(name) == str(name)[::-1]:
print("True")
else:
print("False")
However, there is no need to even set up the if
/else
statement. You can directly print the result of the logical comparison, as shown here:
name = input("Write your word here: ")
input("Press <enter> to check if the word is a palindrome.")
print(str(name) == str(name)[::-1])
If it were an "ordered factor" things would be different. Which is not to say I like "ordered factors", I don't, only to say that some relationships are defined for 'ordered factors' that are not defined for "factors". Factors are thought of as ordinary categorical variables. You are seeing the natural sort order of factors which is alphabetical lexical order for your locale. If you want to get an automatic coercion to "numeric" for every column, ... dates and factors and all, then try:
sapply(df, function(x) max(as.numeric(x)) ) # not generally a useful result
Or if you want to test for factors first and return as you expect then:
sapply( df, function(x) if("factor" %in% class(x) ) {
max(as.numeric(as.character(x)))
} else { max(x) } )
@Darrens comment does work better:
sapply(df, function(x) max(as.character(x)) )
max
does succeed with character vectors.
The reason it doesn't work because some value you passed to the function isn't correct. swift doesn't like Objective-C, you can put nil to arguments which are class type without any restriction(might be). Argument otherButtonTitles is defined as non-optional which its type do not have (?)at its end. so you must pass a concrete value to it.
You can't. There isn't a feature in my CPAN client to do such a thing. We were talking about how we might do something like that at this weekend's Perl QA Workshop, but it's generally hard for all the reasons that Ether mentioned.
You can create your own AuthorizationHandler that will find custom attributes on your Controllers and Actions, and pass them to the HandleRequirementAsync method.
public abstract class AttributeAuthorizationHandler<TRequirement, TAttribute> : AuthorizationHandler<TRequirement> where TRequirement : IAuthorizationRequirement where TAttribute : Attribute
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, TRequirement requirement)
{
var attributes = new List<TAttribute>();
var action = (context.Resource as AuthorizationFilterContext)?.ActionDescriptor as ControllerActionDescriptor;
if (action != null)
{
attributes.AddRange(GetAttributes(action.ControllerTypeInfo.UnderlyingSystemType));
attributes.AddRange(GetAttributes(action.MethodInfo));
}
return HandleRequirementAsync(context, requirement, attributes);
}
protected abstract Task HandleRequirementAsync(AuthorizationHandlerContext context, TRequirement requirement, IEnumerable<TAttribute> attributes);
private static IEnumerable<TAttribute> GetAttributes(MemberInfo memberInfo)
{
return memberInfo.GetCustomAttributes(typeof(TAttribute), false).Cast<TAttribute>();
}
}
Then you can use it for any custom attributes you need on your controllers or actions. For example to add permission requirements. Just create your custom attribute.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public class PermissionAttribute : AuthorizeAttribute
{
public string Name { get; }
public PermissionAttribute(string name) : base("Permission")
{
Name = name;
}
}
Then create a Requirement to add to your Policy
public class PermissionAuthorizationRequirement : IAuthorizationRequirement
{
//Add any custom requirement properties if you have them
}
Then create the AuthorizationHandler for your custom attribute, inheriting the AttributeAuthorizationHandler that we created earlier. It will be passed an IEnumerable for all your custom attributes in the HandleRequirementsAsync method, accumulated from your Controller and Action.
public class PermissionAuthorizationHandler : AttributeAuthorizationHandler<PermissionAuthorizationRequirement, PermissionAttribute>
{
protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionAuthorizationRequirement requirement, IEnumerable<PermissionAttribute> attributes)
{
foreach (var permissionAttribute in attributes)
{
if (!await AuthorizeAsync(context.User, permissionAttribute.Name))
{
return;
}
}
context.Succeed(requirement);
}
private Task<bool> AuthorizeAsync(ClaimsPrincipal user, string permission)
{
//Implement your custom user permission logic here
}
}
And finally, in your Startup.cs ConfigureServices method, add your custom AuthorizationHandler to the services, and add your Policy.
services.AddSingleton<IAuthorizationHandler, PermissionAuthorizationHandler>();
services.AddAuthorization(options =>
{
options.AddPolicy("Permission", policyBuilder =>
{
policyBuilder.Requirements.Add(new PermissionAuthorizationRequirement());
});
});
Now you can simply decorate your Controllers and Actions with your custom attribute.
[Permission("AccessCustomers")]
public class CustomersController
{
[Permission("AddCustomer")]
IActionResult AddCustomer([FromBody] Customer customer)
{
//Add customer
}
}
They are normal symbols as 'a' or '?' or any other. Just (invisible) entries in a string. \r moves cursor to the beginning of the line. \n goes one line down.
As for your replacement, you haven't specified what language you're using, so here's the sketch:
someString.replace("\r\n", "\n").replace("\r", "\n")
How would you check if a variable is a dictionary in Python?
This is an excellent question, but it is unfortunate that the most upvoted answer leads with a poor recommendation, type(obj) is dict
.
(Note that you should also not use dict
as a variable name - it's the name of the builtin object.)
If you are writing code that will be imported and used by others, do not presume that they will use the dict builtin directly - making that presumption makes your code more inflexible and in this case, create easily hidden bugs that would not error the program out.
I strongly suggest, for the purposes of correctness, maintainability, and flexibility for future users, never having less flexible, unidiomatic expressions in your code when there are more flexible, idiomatic expressions.
is
is a test for object identity. It does not support inheritance, it does not support any abstraction, and it does not support the interface.
So I will provide several options that do.
This is the first recommendation I would make, because it allows for users to supply their own subclass of dict, or a OrderedDict
, defaultdict
, or Counter
from the collections module:
if isinstance(any_object, dict):
But there are even more flexible options.
from collections.abc import Mapping
if isinstance(any_object, Mapping):
This allows the user of your code to use their own custom implementation of an abstract Mapping, which also includes any subclass of dict
, and still get the correct behavior.
You commonly hear the OOP advice, "program to an interface".
This strategy takes advantage of Python's polymorphism or duck-typing.
So just attempt to access the interface, catching the specific expected errors (AttributeError
in case there is no .items
and TypeError
in case items
is not callable) with a reasonable fallback - and now any class that implements that interface will give you its items (note .iteritems()
is gone in Python 3):
try:
items = any_object.items()
except (AttributeError, TypeError):
non_items_behavior(any_object)
else: # no exception raised
for item in items: ...
Perhaps you might think using duck-typing like this goes too far in allowing for too many false positives, and it may be, depending on your objectives for this code.
Don't use is
to check types for standard control flow. Use isinstance
, consider abstractions like Mapping
or MutableMapping
, and consider avoiding type-checking altogether, using the interface directly.
Here's a working example, which is a fork of this answer:
$(document).ready(function(){
FB.login(function(response) {
if (response.status == 'connected') {
var user_id = response.authResponse.userID;
var page_id = "40796308305"; // coca cola page https://www.facebook.com/cocacola
var fql_query = "SELECT uid FROM page_fan WHERE page_id="+page_id+" and uid="+user_id;
FB.api({
method: 'fql.query',
query: fql_query
},
function(response){
if (response[0]) {
$("#container_like").show();
} else {
$("#container_notlike").show();
}
}
);
} else {
// user is not logged in
}
});
});
I used the FB.api method (JavaScript SDK), instead of FB.Data.query, which is deprecated. Or you can use the Graph API like with this example:
$(document).ready(function() {
FB.login(function(response) {
if (response.status == 'connected') {
var user_id = response.authResponse.userID;
var page_id = "40796308305"; // coca cola page https://www.facebook.com/cocacola
var fql_query = "SELECT uid FROM page_fan WHERE page_id=" + page_id + " and uid=" + user_id;
FB.api('/me/likes/'+page_id, function(response) {
if (response.data[0]) {
$("#container_like").show();
} else {
$("#container_notlike").show();
}
});
} else {
// user is not logged in
}
});
});?
for Mac OS just go to applications and just run these Scripts Install Certificates.command and Update Shell Profile.command, now it will work.
I tested this and it works fine for me:
from PIL import Image
im = Image.open('image.jpg')
im.show()
CouchDB 0.11 (released at the end of March) is a feature-freeze release for 1.0. This means we'll be maintaining compatibility with the current API for 1.0, so now is a good time to take another look at CouchDB if you haven't in a while.
The CouchDB 0.11 source code release is available here. There are binary installers and other goodies linked here.
I think that there isn't a official naming convention to JSON, but you can follow some industry leaders to see how it is working.
Google, which is one of the biggest IT company of the world, has a JSON style guide: https://google.github.io/styleguide/jsoncstyleguide.xml
Taking advantage, you can find other styles guide, which Google defines, here: https://github.com/google/styleguide
Seems that kramdown supports colors in some form.
Kramdown allows inline html:
This is <span style="color: red">written in red</span>.
Also it has another syntax for including css classes inline:
This is *red*{: style="color: red"}.
This page further explains how GitLab utilizes more compact way to apply css classes in Kramdown:
Applying
blue
class to text:This is a paragraph that for some reason we want blue. {: .blue}
Applying
blue
class to headings:#### A blue heading {: .blue}
Applying two classes:
A blue and bold paragraph. {: .blue .bold}
Applying ids:
#### A blue heading {: .blue #blue-h}
This produces:
<h4 class="blue" id="blue-h">A blue heading</h4>
There is a lot of other stuff explained at above link. You may need to check.
Also, as other answer said, Kramdown is also the default markdown renderer behind Jekyll. So if you are authoring anything on github pages, above functionality might be available out of the box.
My solution (vb.net):
Private Function ConvertToBoolean(p1 As Object) As Boolean
If p1 Is Nothing Then Return False
If IsDBNull(p1) Then Return False
If p1.ToString = "1" Then Return True
If p1.ToString.ToLower = "true" Then Return True
Return False
End Function
This works too
var i = 1;_x000D_
$('button').click(function() {_x000D_
$('#red').clone().appendTo('#test').prop('id', 'red' + i);_x000D_
i++; _x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>_x000D_
<div id="test">_x000D_
<button>Clone</button>_x000D_
<div class="red" id="red">_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<style>_x000D_
.red {_x000D_
width:20px;_x000D_
height:20px;_x000D_
background-color: red;_x000D_
margin: 10px;_x000D_
}_x000D_
</style>
_x000D_
For php7.0-fpm I call:
service php7.0-fpm status
php7.0-fpm start/running, process 25993
Now watch for the good part. The process name is actually php-fpm7.0
echo `/bin/pidof php-fpm7.0`
26334 26297 26286 26285 26282
def lensort(list_1):
list_2=[];list_3=[]
for i in list_1:
list_2.append([i,len(i)])
list_2.sort(key = lambda x : x[1])
for i in list_2:
list_3.append(i[0])
return list_3
This works for me!
Optional.map()
:Takes every element and if the value exists, it is passed to the function:
Optional<T> optionalValue = ...;
Optional<Boolean> added = optionalValue.map(results::add);
Now added has one of three values: true
or false
wrapped into an Optional , if optionalValue
was present, or an empty Optional otherwise.
If you don't need to process the result you can simply use ifPresent()
, it doesn't have return value:
optionalValue.ifPresent(results::add);
Optional.flatMap()
:Works similar to the same method of streams. Flattens out the stream of streams. With the difference that if the value is presented it is applied to function. Otherwise, an empty optional is returned.
You can use it for composing optional value functions calls.
Suppose we have methods:
public static Optional<Double> inverse(Double x) {
return x == 0 ? Optional.empty() : Optional.of(1 / x);
}
public static Optional<Double> squareRoot(Double x) {
return x < 0 ? Optional.empty() : Optional.of(Math.sqrt(x));
}
Then you can compute the square root of the inverse, like:
Optional<Double> result = inverse(-4.0).flatMap(MyMath::squareRoot);
or, if you prefer:
Optional<Double> result = Optional.of(-4.0).flatMap(MyMath::inverse).flatMap(MyMath::squareRoot);
If either the inverse()
or the squareRoot()
returns Optional.empty()
, the result is empty.
lastrow = Sheet1.Range("A#").End(xlDown).Row
This is more easy to determine the row count.
Make sure you declare the right variable when it comes to larger rows.
By the way the '#' sign must be a number where you want to start the row count.