You don't have to bind parameters if you use query builder or eloquent ORM. However, if you use DB::raw()
, ensure that you binding the parameters.
Try the following:
$array = array(1,2,3); $query = DB::table('offers'); $query->select('id', 'business_id', 'address_id', 'title', 'details', 'value', 'total_available', 'start_date', 'end_date', 'terms', 'type', 'coupon_code', 'is_barcode_available', 'is_exclusive', 'userinformations_id', 'is_used'); $query->leftJoin('user_offer_collection', function ($join) use ($array) { $join->on('user_offer_collection.offers_id', '=', 'offers.id') ->whereIn('user_offer_collection.user_id', $array); }); $query->get();
It is very inefficient to store all values in memory, so the objects are reused and loaded one at a time. See this other SO question for a good explanation. Summary:
[...] when looping through the
Iterable
value list, each Object instance is re-used, so it only keeps one instance around at a given time.
If you aren't using fetchBusinesses method anywhere apart from the effect, you could simply move it into the effect and avoid the warning
useEffect(() => {
const fetchBusinesses = () => {
return fetch("theURL", {method: "GET"}
)
.then(res => normalizeResponseErrors(res))
.then(res => {
return res.json();
})
.then(rcvdBusinesses => {
// some stuff
})
.catch(err => {
// some error handling
});
};
fetchBusinesses();
}, []);
If however you are using fetchBusinesses outside of render, you must note two things
fetchBusinesses
as a method when it's used during mount with its enclosing closure?To sum it up I would say that if you are using fetchBusinesses
outside of useEffect
you can disable the rule using // eslint-disable-next-line react-hooks/exhaustive-deps
otherwise you can move the method inside of useEffect
To disable the rule you would write it like
useEffect(() => {
// other code
...
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
I have same problem after upgrading to Gradle Wrapper 5.1.rec3. I am back to Gradle 4.6
This is worked in my case:
pip install --user --upgrade pip
Otherwise open command prompt with Run as administrator and do the same thing.
This is acceptable as assigning to an array. But if you are asking for pushing, I am pretty sure its not possible in array. Rather it can be achieved by using Stack, Queue or any other data structure. Real arrays doesn't have such functions. But derived classes such as ArrayList have it.
I would suggest updating git. If you downloaded the .pkg
then be sure to uninstall it first.
Go to preferences(settings) : click on Build,Execution,Deployment .....then select : Instant Run ......and uncheck its topmost checkbox (i.e Disable Instant Run)
1. Without plugin
class IndiSampleState extends State<ProgHudPage> {
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('Demo'),
),
body: Center(
child: RaisedButton(
color: Colors.blueAccent,
child: Text('Login'),
onPressed: () async {
showDialog(
context: context,
builder: (BuildContext context) {
return Center(child: CircularProgressIndicator(),);
});
await loginAction();
Navigator.pop(context);
},
),
));
}
Future<bool> loginAction() async {
//replace the below line of code with your login request
await new Future.delayed(const Duration(seconds: 2));
return true;
}
}
2. With plugin
check this plugin progress_hud
add the dependency in the pubspec.yaml file
dev_dependencies:
progress_hud:
import the package
import 'package:progress_hud/progress_hud.dart';
Sample code is given below to show and hide the indicator
class ProgHudPage extends StatefulWidget {
@override
_ProgHudPageState createState() => _ProgHudPageState();
}
class _ProgHudPageState extends State<ProgHudPage> {
ProgressHUD _progressHUD;
@override
void initState() {
_progressHUD = new ProgressHUD(
backgroundColor: Colors.black12,
color: Colors.white,
containerColor: Colors.blue,
borderRadius: 5.0,
loading: false,
text: 'Loading...',
);
super.initState();
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('ProgressHUD Demo'),
),
body: new Stack(
children: <Widget>[
_progressHUD,
new Positioned(
child: RaisedButton(
color: Colors.blueAccent,
child: Text('Login'),
onPressed: () async{
_progressHUD.state.show();
await loginAction();
_progressHUD.state.dismiss();
},
),
bottom: 30.0,
right: 10.0)
],
));
}
Future<bool> loginAction()async{
//replace the below line of code with your login request
await new Future.delayed(const Duration(seconds: 2));
return true;
}
}
If you don't want to grant admin permission to dashboard service account, you can create cluster admin service account.
$ kubectl create serviceaccount cluster-admin-dashboard-sa
$ kubectl create clusterrolebinding cluster-admin-dashboard-sa \
--clusterrole=cluster-admin \
--serviceaccount=default:cluster-admin-dashboard-sa
And then, you can use the token of just created cluster admin service account.
$ kubectl get secret | grep cluster-admin-dashboard-sa
cluster-admin-dashboard-sa-token-6xm8l kubernetes.io/service-account-token 3 18m
$ kubectl describe secret cluster-admin-dashboard-sa-token-6xm8l
I quoted it from giantswarm guide - https://docs.giantswarm.io/guides/install-kubernetes-dashboard/
The Best way:
Connect again
Run again
You can make use of history.listen()
function when trying to detect the route change. Considering you are using react-router v4
, wrap your component with withRouter
HOC to get access to the history
prop.
history.listen()
returns an unlisten
function. You'd use this to unregister
from listening.
You can configure your routes like
index.js
ReactDOM.render(
<BrowserRouter>
<AppContainer>
<Route exact path="/" Component={...} />
<Route exact path="/Home" Component={...} />
</AppContainer>
</BrowserRouter>,
document.getElementById('root')
);
and then in AppContainer.js
class App extends Component {
componentWillMount() {
this.unlisten = this.props.history.listen((location, action) => {
console.log("on route change");
});
}
componentWillUnmount() {
this.unlisten();
}
render() {
return (
<div>{this.props.children}</div>
);
}
}
export default withRouter(App);
From the history docs:
You can listen for changes to the current location using
history.listen
:history.listen((location, action) => { console.log(`The current URL is ${location.pathname}${location.search}${location.hash}`) console.log(`The last navigation action was ${action}`) })
The location object implements a subset of the window.location interface, including:
**location.pathname** - The path of the URL **location.search** - The URL query string **location.hash** - The URL hash fragment
Locations may also have the following properties:
location.state - Some extra state for this location that does not reside in the URL (supported in
createBrowserHistory
andcreateMemoryHistory
)
location.key
- A unique string representing this location (supported increateBrowserHistory
andcreateMemoryHistory
)The action is one of
PUSH, REPLACE, or POP
depending on how the user got to the current URL.
When you are using react-router v3 you can make use of history.listen()
from history
package as mentioned above or you can also make use browserHistory.listen()
You can configure and use your routes like
import {browserHistory} from 'react-router';
class App extends React.Component {
componentDidMount() {
this.unlisten = browserHistory.listen( location => {
console.log('route changes');
});
}
componentWillUnmount() {
this.unlisten();
}
render() {
return (
<Route path="/" onChange={yourHandler} component={AppContainer}>
<IndexRoute component={StaticContainer} />
<Route path="/a" component={ContainerA} />
<Route path="/b" component={ContainerB} />
</Route>
)
}
}
I tried to generate a form dynamically because the amount of questions depend on an object and for me the error was fixed when I added ngDefaultControl
to my mat-form-field
.
<form [formGroup]="questionsForm">
<ng-container *ngFor="let question of questions">
<mat-form-field [formControlName]="question.id" ngDefaultControl>
<mat-label>{{question.questionContent}}</mat-label>
<textarea matInput rows="3" required></textarea>
</mat-form-field>
</ng-container>
<button mat-raised-button (click)="sendFeedback()">Submit all questions</button>
</form>
In sendFeedback() I get the value from my dynamic form by selecting the formgroup's value as such
sendFeedbackAsAgent():void {
if (this.questionsForm.valid) {
console.log(this.questionsForm.value)
}
}
You could use the CSS calc
parameter to calculate the height dynamically like so:
.dynamic-height {_x000D_
color: #000;_x000D_
font-size: 12px;_x000D_
margin-top: calc(100% - 10px);_x000D_
text-align: left;_x000D_
}
_x000D_
<div class='dynamic-height'>_x000D_
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem.</p>_x000D_
</div>
_x000D_
i was surprised to find that when i had a class that was closed it produced this vague error. changing it to a open class resolved the issue.
before:
class DefaultSubscriber<T> : Observer<T> {//...
}
after:
open class DefaultSubscriber<T> : Observer<T> {//...
}
There is no BI project in Visual Studio. Youll need to download SSDT. SSDT 2017 works fine :)
https://docs.microsoft.com/en-us/sql/ssdt/download-sql-server-data-tools-ssdt
To navigate to another component you can use this.props.history.push('/main');
import React, { Component, Fragment } from 'react'
class Example extends Component {
redirect() {
this.props.history.push('/main')
}
render() {
return (
<Fragment>
{this.redirect()}
</Fragment>
);
}
}
export default Example
Let's stick to the solution from the linked question (Changing color scale in seaborn bar plot). You want to use argsort to determine the order of the colors to use for colorizing the bars. In the linked question argsort is applied to a Series object, which works fine, while here you have a DataFrame. So you need to select one column of that DataFrame to apply argsort on.
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
df = sns.load_dataset("tips")
groupedvalues=df.groupby('day').sum().reset_index()
pal = sns.color_palette("Greens_d", len(groupedvalues))
rank = groupedvalues["total_bill"].argsort().argsort()
g=sns.barplot(x='day',y='tip',data=groupedvalues, palette=np.array(pal[::-1])[rank])
for index, row in groupedvalues.iterrows():
g.text(row.name,row.tip, round(row.total_bill,2), color='black', ha="center")
plt.show()
rank()
starts at 1
instead of zero. So one has to subtract 1 from the array. Also for indexing we need integer values, so we need to cast it to int
.
rank = groupedvalues['total_bill'].rank(ascending=True).values
rank = (rank-1).astype(np.int)
For those who are experiencing same problem after controlling there is no suspicious java process which allocate the port, there is no red square on eclipse to terminate any process and also there is no change even you try different port for your spring boot application.
might sound stupid but; restarting eclipse works. :)
My system version: ubuntu 20.04 LTS.
I solved this by generate a new MOK and enroll it into shim.
Without disable of Secure Boot, although it also really works for me.
Simply execute this command and follow what it suggests:
sudo update-secureboot-policy --enroll-key
According to ubuntu's wiki: How can I do non-automated signing of drivers
In the v-model the value of the property might not be a strict boolean value and the checkbox might not 'recognise' the value as checked/unchecked. There is a neat feature in VueJS to make the conversion to true or false:
<input
type="checkbox"
v-model="toggle"
true-value="yes"
false-value="no"
>
This might be because the browser cannot access a file. I stumbled with this type of error when creating application with node.js. You can try to directly request the script file (copying and pasting url) and see if you can retrieve it. You can see then what the real problem is. It can be because of permission of folder in which the file is located, or browser just cannot find it due to incorrect path to it. In node.js, after specifying route to file, all works.
The root cause for the question asked was the deployment/job/replicasets spec attribute strategy->type
which defines what should happen when the pod will be destroyed (either implicitly or explicitly). In my case, it was Recreate
.
As per @nomad's answer, deleting the deployment/job/replicasets is the simple fix to avoid experimenting with deadly combos before messing up the cluster as a novice user.
Try the following commands to understand the behind the scene actions before jumping into debugging :
kubectl get all -A -o name
kubectl get events -A | grep <pod-name>
Even without looking at assembly, the most obvious reason is that /= 2
is probably optimized as >>=1
and many processors have a very quick shift operation. But even if a processor doesn't have a shift operation, the integer division is faster than floating point division.
Edit: your milage may vary on the "integer division is faster than floating point division" statement above. The comments below reveal that the modern processors have prioritized optimizing fp division over integer division. So if someone were looking for the most likely reason for the speedup which this thread's question asks about, then compiler optimizing /=2
as >>=1
would be the best 1st place to look.
On an unrelated note, if n
is odd, the expression n*3+1
will always be even. So there is no need to check. You can change that branch to
{
n = (n*3+1) >> 1;
count += 2;
}
So the whole statement would then be
if (n & 1)
{
n = (n*3 + 1) >> 1;
count += 2;
}
else
{
n >>= 1;
++count;
}
Most probably you have dependent imports.
In my case I used a serializer class as a parameter in my model, and the serializer class was using this model: serializer_class = AccountSerializer
from ..api.serializers import AccountSerializer
class Account(AbstractBaseUser):
serializer_class = AccountSerializer
...
And in the "serializers" file:
from ..models import Account
class AccountSerializer(serializers.ModelSerializer):
class Meta:
model = Account
fields = (
'id', 'email', 'date_created', 'date_modified',
'firstname', 'lastname', 'password', 'confirm_password')
...
For those who came here looking for the answer and didnt type 3306 wrong...If like myself, you have wasted hours with no luck searching for this answer, then possibly this may help.
If you are seeing this: (HY000/2002): No connection could be made because the target machine actively refused it
Then my understanding is that it cant connect for one of the following below. Now which..
1) is your wamp, mamp, etc icon GREEN? Either way, right-click the icon --> click tools --> test both the port used for Apache (typically 80) and for Mariadb (3307?). Should say 'It is correct' for both.
2) Error comes from a .php file. So, check your dbconnect.php.
<?php
$servername = "localhost";
$username = "your_username";
$password = "your_pw";
$dbname = "your_dbname";
$port = "3307";
?>
Is your setup correct? Does your user exist? Do they have rights? Does port match the tested port in 1)? Doesn't have to be 3307 and user can be root. You can also left click the green icon --> click MariaDB and view used port as shown in the image below. All good? Positive? ok!
3) Error comes when you login to phpmyadmin. So, check your my.ini.
Open my.ini by left clicking the green icon --> click MariaDB -->
; The following options will be passed to all MariaDB clients
[client]
;password = your_password
port = 3307
socket = /tmp/mariadb.sock
; Here follows entries for some specific programs
; The MariaDB server
[wampmariadb64]
;skip-grant-tables
port = 3307
socket = /tmp/mariadb.sock
Make sure the ports match the port MariaDB is being testing on. Then finally..
[mysqld]
port = 3307
At the bottom of my.ini, make sure this port matches as well.
4) 1-3 done? restart your WAMP and cross your fingers!
You can also use OPENROWSET to import excel file in sql server.
SELECT * INTO Your_Table FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
'Excel 12.0;Database=C:\temp\MySpreadsheet.xlsx',
'SELECT * FROM [Data$]')
For jquery-ui-dragable with jquery-ui-touch-punch I fixed it similar to Iván Rodríguez, but with one more event override for touchmove:
jQuery.event.special.touchstart = {
setup: function( _, ns, handle ) {
this.addEventListener('touchstart', handle, { passive: !ns.includes('noPreventDefault') });
}
};
jQuery.event.special.touchmove = {
setup: function( _, ns, handle ) {
this.addEventListener('touchmove', handle, { passive: !ns.includes('noPreventDefault') });
}
};
The raw.githubusercontent.com
domain is used to serve unprocessed versions of files stored in GitHub repositories. If you browse to a file on GitHub and then click the Raw link, that's where you'll go.
The URL in your question references the install
file in the master
branch of the Homebrew/install
repository. The rest of that command just retrieves the file and runs ruby
on its contents.
I do not know how to solve this using code, but I do manually adjust the control panel at the right bottom in the plot figure, and adjust the figure size like:
f, ax = plt.subplots(figsize=(16, 12))
at the meantime until you get a matched size colobar. This worked for me.
I got a GPU called NVIDIA GTX GeForce 1650 Ti
in my machine with tensorflow-gpu==2.2.0
Run the following two lines of code:
import tensorflow as tf
print("Num GPUs Available: ", len(tf.config.experimental.list_physical_devices('GPU')))
Output:
Num GPUs Available: 1
Merlin's answer is better and super easy, but we don't need a lambda function. The evaluation of dictionary can be safely ignored by either of the following two ways as illustrated below:
Way 1: Two steps
# step 1: convert the `Pollutants` column to Pandas dataframe series
df_pol_ps = data_df['Pollutants'].apply(pd.Series)
df_pol_ps:
a b c
0 46 3 12
1 36 5 8
2 NaN 2 7
3 NaN NaN 11
4 82 NaN 15
# step 2: concat columns `a, b, c` and drop/remove the `Pollutants`
df_final = pd.concat([df, df_pol_ps], axis = 1).drop('Pollutants', axis = 1)
df_final:
StationID a b c
0 8809 46 3 12
1 8810 36 5 8
2 8811 NaN 2 7
3 8812 NaN NaN 11
4 8813 82 NaN 15
Way 2: The above two steps can be combined in one go:
df_final = pd.concat([df, df['Pollutants'].apply(pd.Series)], axis = 1).drop('Pollutants', axis = 1)
df_final:
StationID a b c
0 8809 46 3 12
1 8810 36 5 8
2 8811 NaN 2 7
3 8812 NaN NaN 11
4 8813 82 NaN 15
I was having the same issue when tried with the syntax "ng new " and solved that simply by updating the existing node version from 5.x.x to 8.x.x. After successful updation of node, the syntax worked perfectly for me. Please update the existing version of node. As it is clearly mentioned in angular documentation that these commands require the node version >= 6.9.x. For reference please check https://angular.io/guide/quickstart. It clearly states "Verify that you are running at least node 6.9.x and npm 3.x.x by running node -v and npm -v in a terminal/console window. Older versions produce errors, but newer versions are fine".
Assume I have below array:
Skins[
{Id: 1, Name: "oily skin"},
{Id: 2, Name: "dry skin"}
];
If we want to get item with Id = 1
and Name = "oily skin"
, We'll try as below:
var skinName = skins.find(x=>x.Id == "1").Name;
The result will return the skinName is "Oily skin".
Running Visual Studio Code as Administrator should do the trick.
If you're on Windows you can:
Make sure you have all other instances of VS Code closed and then try to run as Administrator. The electron framework likes to stall processes when closing them so it's best to check your task manager and kill the remaining processes.
Related Changes in CodebaseIf for some weird reason this is not running your commands as an Administrator you can try the runas
command. Microsoft: runas command
runas /user:Administrator myCommand
runas "/user:First Last" "my command"
Arhhh this got me and I spent a lot of time troubleshooting it. The problem was my tests were being executed in Parellel (the default with XUnit).
To make my test run sequentially I decorated each class with this attribute:
[Collection("Sequential")]
This is how I worked it out: Execute unit tests serially (rather than in parallel)
I mock up my EF In Memory context with GenFu:
private void CreateTestData(TheContext dbContext)
{
GenFu.GenFu.Configure<Employee>()
.Fill(q => q.EmployeeId, 3);
var employee = GenFu.GenFu.ListOf<Employee>(1);
var id = 1;
GenFu.GenFu.Configure<Team>()
.Fill(p => p.TeamId, () => id++).Fill(q => q.CreatedById, 3).Fill(q => q.ModifiedById, 3);
var Teams = GenFu.GenFu.ListOf<Team>(20);
dbContext.Team.AddRange(Teams);
dbContext.SaveChanges();
}
When Creating Test Data, from what I can deduct, it was alive in two scopes (once in the Employee's Tests while the Team tests were running):
public void Team_Index_should_return_valid_model()
{
using (var context = new TheContext(CreateNewContextOptions()))
{
//Arrange
CreateTestData(context);
var controller = new TeamController(context);
//Act
var actionResult = controller.Index();
//Assert
Assert.NotNull(actionResult);
Assert.True(actionResult.Result is ViewResult);
var model = ModelFromActionResult<List<Team>>((ActionResult)actionResult.Result);
Assert.Equal(20, model.Count);
}
}
Wrapping both Test Classes with this sequential collection attribute has cleared the apparent conflict.
[Collection("Sequential")]
Additional references:
https://github.com/aspnet/EntityFrameworkCore/issues/7340
EF Core 2.1 In memory DB not updating records
http://www.jerriepelser.com/blog/unit-testing-aspnet5-entityframework7-inmemory-database/
http://gunnarpeipman.com/2017/04/aspnet-core-ef-inmemory/
https://github.com/aspnet/EntityFrameworkCore/issues/12459
Preventing tracking issues when using EF Core SqlLite in Unit Tests
with open('writing_file.json', 'w') as w:
with open('reading_file.json', 'r') as r:
for line in r:
element = json.loads(line.strip())
if 'hours' in element:
del element['hours']
w.write(json.dumps(element))
this is the method i use..
My problem was that my company proxy was getting in the way. The solution here was to identify the Root CA / certificate chain of our proxy, (on mac) export it from the keychain in .pem format, then export a variable for node to use.
export NODE_EXTRA_CA_CERTS=/path/to/your/CA/cert.pem
You could just comment the maven dependency for a while:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<!-- <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>-->
</dependencies>
It worked fine for me
Disabling it from
application.properties
is deprecated for Spring Boot 2.0
In case than you want to store a complex command to compare text result, for example to compare the version of OS, maybe this can help you:
tasks:
- shell: echo $(cat /etc/issue | awk {'print $7'})
register: echo_content
- shell: echo "It works"
when: echo_content.stdout == "12"
register: out
- debug: var=out.stdout_lines
for tensorflow 2.1.0, following code works fine.
import tensorflow as tf
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)
In my case after invalidate cache and restart the android studio fixed the problem .To do that go to
File -> invalidate cache / Restart
There is no magic method that will do what you want. The answer is simply name it appropriately. asdict
is a reasonable choice for a plain conversion to dict
, inspired primarily by namedtuple
. However, your method will obviously contain special logic that might not be immediately obvious from that name; you are returning only a subset of the class' state. If you can come up with with a slightly more verbose name that communicates the concepts clearly, all the better.
Other answers suggest using __iter__
, but unless your object is truly iterable (represents a series of elements), this really makes little sense and constitutes an awkward abuse of the method. The fact that you want to filter out some of the class' state makes this approach even more dubious.
PuTTY can't find where your X server is, because you didn't tell it. (ssh on Linux doesn't have this problem because it runs under X so it just uses that one.) Fill in the blank box after "X display location" with your Xming server's address.
Alternatively, try MobaXterm. It has an X server builtin.
I found out that it also happens if you uninstalled some packages from your react-native project and there is still packages in your build gradle dependencies in the bottom of page like:
{
project(':react-native-sound-player')
}
You don't need to install curl
to download the file into Docker container, use ADD
command, e.g.
ADD https://raw.githubusercontent.com/Homebrew/install/master/install /tmp
RUN ruby -e /tmp/install
Note: Add above lines to your Dockerfile
file.
Another example which installs Azure CLI:
ADD https://aka.ms/InstallAzureCLIDeb /tmp
RUN bash /tmp/InstallAzureCLIDeb
The registry path for official images (without a slash in the name) is library/<image>
. Try this instead:
docker pull registry.hub.docker.com/library/busybox
Because all previous answers doesn't work for me for ubuntu 14.04 here what I did, if any one get the same problem:
git clone https://github.com/Linuxbrew/brew.git ~/.linuxbrew
PATH="$HOME/.linuxbrew/bin:$PATH"
export MANPATH="$(brew --prefix)/share/man:$MANPATH"
export INFOPATH="$(brew --prefix)/share/info:$INFOPATH"
then
sudo apt-get install gawk
sudo yum install gawk
brew install hello
you can follow this link for more information.
partial interface Navigator { readonly attribute boolean webdriver; };
The webdriver IDL attribute of the Navigator interface must return the value of the webdriver-active flag, which is initially false.
This property allows websites to determine that the user agent is under control by WebDriver, and can be used to help mitigate denial-of-service attacks.
Taken directly from the 2017 W3C Editor's Draft of WebDriver. This heavily implies that at the very least, future iterations of selenium's drivers will be identifiable to prevent misuse. Ultimately, it's hard to tell without the source code, what exactly causes chrome driver in specific to be detectable.
Just increase the -webkit-line-clamp: 4; to increase the number of lines
p {
display: -webkit-box;
max-width: 200px;
-webkit-line-clamp: 4;
-webkit-box-orient: vertical;
overflow: hidden;
}
_x000D_
<p>Lorem ipsum dolor sit amet, novum menandri adversarium ad vim, ad his persius nostrud conclusionemque. Ne qui atomorum pericula honestatis. Te usu quaeque detracto, idque nulla pro ne, ponderum invidunt eu duo. Vel velit tincidunt in, nulla bonorum id eam, vix ad fastidii consequat definitionem.</p>
_x000D_
Line clamp is a proprietary and undocumented CSS (webkit) : https://caniuse.com/#feat=css-line-clamp, so it currently work on only few browsers.
Removed duplicated 'display' property + removed unnecessary 'text-overflow: ellipsis'.
With React 16.6.3 and @Material UI 3.5.1, I am using arrays in className like className={[classes.tableCell, classes.capitalize]}
Try something like the following in your case.
class Pill extends React.Component {
render() {
return (
<button className={['pill', this.props.styleName]}>{this.props.children}</button>
);
}
}
I will add an option to VitalyB's answer:
Option 3
Via npm. If you run your commands via npm, then you could add this setup to your package.json (check out also the webpack.config.js there too). For developing run npm start
, no need to copy index.html in this case because the web server will be run from the source files directory, and the bundle.js will be available from the same place (the bundle.js will live in memory only but will available as if it was located together with index.html). For production run npm run build
and a dist folder will contain your bundle.js and index.html gets copied with good old cp-command, as you can see below:
"scripts": {
"test": "NODE_ENV=test karma start",
"start": "node node_modules/.bin/webpack-dev-server --content-base app",
"build": "NODE_ENV=production node node_modules/.bin/webpack && cp app/index.html dist/index.html"
}
Update: Option 4
There is a copy-webpack-plugin, as described in this Stackoverflow answer
But generally, except for the very "first" file (like index.html) and larger assets (like large images or video), include the css, html, images and so on directly in your app via require
and webpack will include it for you (well, after you set it up correctly with loaders and possibly plugins).
Reasons caused this issue:
SOLUTION:
-----------------SOLUTION 1---------------
Create a custom LinearLayoutManager as the following and set it to the ReyclerView
public class CustomLinearLayoutManager extends LinearLayoutManager {
//Generate constructors
@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
try {
super.onLayoutChildren(recycler, state);
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, "Inconsistency detected");
}
}
}
Then set RecyclerVIew Layout Manager as follow:
recyclerView.setLayoutManager(new CustomLinearLayoutManager(activity));
-----------------SOLUTION 2---------------
Again, create a custom Linear Layout Manager as follow:
public class CustomLinearLayoutManager extends LinearLayoutManager {
//Generate constructors
@Override
public boolean supportsPredictiveItemAnimations() {
return false;
}
}
Then set RecyclerVIew Layout Manager as follow:
recyclerView.setLayoutManager(new CustomLinearLayoutManager(activity));
-----------------SOLUTION 3---------------
-----------------SOLUTION 4---------------
The <NAME>
you use in multer's upload.single(<NAME>)
function must be the same as the one you use in <input type="file" name="<NAME>" ...>
.
So you need to change
var type = upload.single('file')
to
var type = upload.single('recfile')
in you app.js
Hope this helps.
Try docker inspect
, for example:
$ docker inspect --type=image treeder/hello.rb:nada
Error: No such image: treeder/hello.rb:nada
[]
But now with an image that exists, you'll get a bunch of information, eg:
$ docker inspect --type=image treeder/hello.rb:latest
[
{
"Id": "85c5116a2835521de2c52f10ab5dda0ff002a4a12aa476c141aace9bc67f43ad",
"Parent": "ecf63f5eb5e89e5974875da3998d72abc0d3d0e4ae2354887fffba037b356ad5",
"Comment": "",
"Created": "2015-09-23T22:06:38.86684783Z",
...
}
]
And it's in a nice json format.
My problem was with TIMEZONE
in emulator genymotion. Change TIMEZONE ANDROID EMULATOR
equal TIMEZONE SERVER
, solved problem.
If you are using intellij and want to use gradle you need to add this to the dependencies section of build.gradle file:
testImplementation("org.junit.jupiter:junit-jupiter-api:5.4.2")
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.4.2")
Related answer with this question.
Error - fatal: I don't handle protocol 'git clone https'
I was trying to clone git project to my newly installed VScode in my Linux system, i was copied the entire url from bit bucket, which was like
But actually it running command like
git clone git clone https://[email protected]/abcuser/myproject.git
in the bit bucket.
So Simply do the following steps :
1. Enter Ctr+p; this will open command box. Enter and open 'Clone'
2. Now only paste the url of your git reposiratory here. eg: https://[email protected]/abcuser/myproject.git
3. After that box for enter your git password will appear on screen. Enter your git password here.
4. Done.
The best solution I found when dealing with Typescript classes and json objects: add a constructor in your Typescript class that takes the json data as parameter. In that constructor you extend your json object with jQuery, like this: $.extend( this, jsonData). $.extend allows keeping the javascript prototypes while adding the json object's properties.
export class Foo
{
Name: string;
getName(): string { return this.Name };
constructor( jsonFoo: any )
{
$.extend( this, jsonFoo);
}
}
In your ajax callback, translate your jsons in a your typescript object like this:
onNewFoo( jsonFoos : any[] )
{
let receviedFoos = $.map( jsonFoos, (json) => { return new Foo( json ); } );
// then call a method:
let firstFooName = receviedFoos[0].GetName();
}
If you don't add the constructor, juste call in your ajax callback:
let newFoo = new Foo();
$.extend( newFoo, jsonData);
let name = newFoo.GetName()
...but the constructor will be useful if you want to convert the children json object too. See my detailed answer here.
Using $ docker inspect
Incase the Image has no /bin/bash
in the output, you can use command below: it worked for me perfectly
$ docker exec -it <container id> sh
I also had the same problem. I use "Postman" for JSON request. The code itself is not wrong. I simply set the content type to JSON (application/json
) and it worked, as you can see on the image below
You can use an async result and a delegate for this. If you read up on the documentation it should make it pretty clear what to do. I can write up some sample code if you like and attach it to this answer.
Action isExcelInteractive = IsExcelInteractive;
private async void btnOk_Click(object sender, EventArgs e)
{
IAsyncResult result = isExcelInteractive.BeginInvoke(ItIsDone, null);
result.AsyncWaitHandle.WaitOne();
Console.WriteLine("YAY");
}
static void IsExcelInteractive(){
while (something_is_false) // do your check here
{
if(something_is_true)
return true;
}
Thread.Sleep(1);
}
void ItIsDone(IAsyncResult result)
{
this.isExcelInteractive.EndInvoke(result);
}
Apologies if this code isn't 100% complete, I don't have Visual Studio on this computer, but hopefully it gets you where you need to get to.
I had this problem recently where apt install wget
does not find anything. As it turns out apt update
was never run.
apt update
apt install wget
After discussing this with a coworker we mused that apt update
is likely not run in order to save both time and space in the docker image.
In a discussion, Simon clearly mentioned that:
While the datatype used for storing the list of handles may be ordered by insertion, the order in which the WebDriver implementation iterates over the window handles to insert them has no requirement to be stable. The ordering is arbitrary.
Using Selenium v3.x opening a website in a New Tab through Python is much easier now. We have to induce an WebDriverWait for number_of_windows_to_be(2)
and then collect the window handles every time we open a new tab/window and finally iterate through the window handles and switchTo().window(newly_opened)
as required. Here is a solution where you can open http://www.google.co.in
in the initial TAB and https://www.yahoo.com
in the adjacent TAB:
Code Block:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
options = webdriver.ChromeOptions()
options.add_argument("start-maximized")
options.add_argument('disable-infobars')
driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
driver.get("http://www.google.co.in")
print("Initial Page Title is : %s" %driver.title)
windows_before = driver.current_window_handle
print("First Window Handle is : %s" %windows_before)
driver.execute_script("window.open('https://www.yahoo.com')")
WebDriverWait(driver, 10).until(EC.number_of_windows_to_be(2))
windows_after = driver.window_handles
new_window = [x for x in windows_after if x != windows_before][0]
driver.switch_to_window(new_window)
print("Page Title after Tab Switching is : %s" %driver.title)
print("Second Window Handle is : %s" %new_window)
Console Output:
Initial Page Title is : Google
First Window Handle is : CDwindow-B2B3DE3A222B3DA5237840FA574AF780
Page Title after Tab Switching is : Yahoo
Second Window Handle is : CDwindow-D7DA7666A0008ED91991C623105A2EC4
Browser Snapshot:
You can find the java based discussion in Best way to keep track and iterate through tabs and windows using WindowHandles using Selenium
With the kind help from Tim Williams, I finally figured out the last détails that were missing. Here's the final code below.
Private Sub Open_multiple_sub_pages_from_main_page()
Dim i As Long
Dim IE As Object
Dim Doc As Object
Dim objElement As Object
Dim objCollection As Object
Dim buttonCollection As Object
Dim valeur_heure As Object
' Create InternetExplorer Object
Set IE = CreateObject("InternetExplorer.Application")
' You can uncoment Next line To see form results
IE.Visible = True
' Send the form data To URL As POST binary request
IE.navigate "http://webpage.com/"
' Wait while IE loading...
While IE.Busy
DoEvents
Wend
Set objCollection = IE.Document.getElementsByTagName("input")
i = 0
While i < objCollection.Length
If objCollection(i).Name = "txtUserName" Then
' Set text for search
objCollection(i).Value = "1234"
End If
If objCollection(i).Name = "txtPwd" Then
' Set text for search
objCollection(i).Value = "password"
End If
If objCollection(i).Type = "submit" And objCollection(i).Name = "btnSubmit" Then ' submit button if found and set
Set objElement = objCollection(i)
End If
i = i + 1
Wend
objElement.Click ' click button to load page
' Wait while IE re-loading...
While IE.Busy
DoEvents
Wend
' Show IE
IE.Visible = True
Set Doc = IE.Document
Dim links, link
Dim j As Integer 'variable to count items
j = 0
Set links = IE.Document.getElementById("dgTime").getElementsByTagName("a")
n = links.Length
While j <= n 'loop to go thru all "a" item so it loads next page
links(j).Click
While IE.Busy
DoEvents
Wend
'-------------Do stuff here: copy field value and paste in excel sheet. Will post another question for this------------------------
IE.Document.getElementById("DetailToolbar1_lnkBtnSave").Click 'save
Do While IE.Busy
Application.Wait DateAdd("s", 1, Now) 'wait
Loop
IE.Document.getElementById("DetailToolbar1_lnkBtnCancel").Click 'close
Do While IE.Busy
Application.Wait DateAdd("s", 1, Now) 'wait
Loop
Set links = IE.Document.getElementById("dgTime").getElementsByTagName("a")
j = j + 2
Wend
End Sub
The request type is multipart/form-data and what you are sending is essentially form fields that go out as bytes with content boundaries separating different form fields.To send an object representation as form field (string), you can send a serialized form from the client that you can then deserialize on the server.
After all no programming environment object is actually ever traveling on the wire. The programming environment on both side are just doing automatic serialization and deserialization that you can also do. That is the cleanest and programming environment quirks free way to do it.
As an example, here is a javascript client posting to a Jersey example service,
submitFile(){
let data = new FormData();
let account = {
"name": "test account",
"location": "Bangalore"
}
data.append('file', this.file);
data.append("accountKey", "44c85e59-afed-4fb2-884d-b3d85b051c44");
data.append("device", "test001");
data.append("account", JSON.stringify(account));
let url = "http://localhost:9090/sensordb/test/file/multipart/upload";
let config = {
headers: {
'Content-Type': 'multipart/form-data'
}
}
axios.post(url, data, config).then(function(data){
console.log('SUCCESS!!');
console.log(data.data);
}).catch(function(){
console.log('FAILURE!!');
});
},
Here the client is sending a file, 2 form fields (strings) and an account object that has been stringified for transport. here is how the form fields look on the wire,
On the server, you can just deserialize the form fields the way you see fit. To finish this trivial example,
@POST
@Path("/file/multipart/upload")
@Consumes({MediaType.MULTIPART_FORM_DATA})
public Response uploadMultiPart(@Context ContainerRequestContext requestContext,
@FormDataParam("file") InputStream fileInputStream,
@FormDataParam("file") FormDataContentDisposition cdh,
@FormDataParam("accountKey") String accountKey,
@FormDataParam("account") String json) {
System.out.println(cdh.getFileName());
System.out.println(cdh.getName());
System.out.println(accountKey);
try {
Account account = Account.deserialize(json);
System.out.println(account.getLocation());
System.out.println(account.getName());
} catch (Exception e) {
e.printStackTrace();
}
return Response.ok().build();
}
I noticed that the error was caused by me passing table field names as variables i.e. I sent:
$stmt = $this->con->prepare("INSERT INTO tester ($test1, $test2) VALUES (?, ?)");
instead of:
$stmt = $this->con->prepare("INSERT INTO tester (test1, test2) VALUES (?, ?)");
Please note the table field names contained $
before field names. They should not be there such that $field1
should be field1
.
Swift 4,
private func callNumber(phoneNumber:String) {
if let phoneCallURL = URL(string: "telprompt://\(phoneNumber)") {
let application:UIApplication = UIApplication.shared
if (application.canOpenURL(phoneCallURL)) {
if #available(iOS 10.0, *) {
application.open(phoneCallURL, options: [:], completionHandler: nil)
} else {
// Fallback on earlier versions
application.openURL(phoneCallURL as URL)
}
}
}
}
This problem was bugg me for hours. I was using Nextjs and trying to convert canvas to an image file.
I just use the other guy's solution but the created file was empty.
So if this is your problem you should mention the size property in the file object.
new File([Blob], `my_image${new Date()}.jpeg`, {
type: "image/jpeg",
lastModified: new Date(),
size: 2,
});
just add it, the value it's not important.
this.setState({ abc.xyz: 'new value' });
syntax is not allowed.
You have to pass the whole object.
this.setState({abc: {xyz: 'new value'}});
If you have other variables in abc
var abc = this.state.abc;
abc.xyz = 'new value';
this.setState({abc: abc});
You can have ordinary variables, if they don't rely on this.props and this.state
.
After 1.13.0, Docker includes a new command docker system df
to show docker disk usage.
$ docker system df
TYPE TOTAL ACTIVE SIZE RECLAIMABLE
Images 5 1 2.777 GB 2.647 GB (95%)
Containers 1 1 0 B 0B
Local Volumes 4 1 3.207 GB 2.261 (70%)
To show more detailed information on space usage:
$ docker system df --verbose
When the length of v will be zero, it'll give you the value error.
You should check the length or you should check the list first whether it is none or not.
if list:
k.index(max(list))
or
len(list)== 0
If you are looking for a way to "mount" files, like -v
for docker run
, you can now use the --secret
flag for docker build
echo 'WARMACHINEROX' > mysecret.txt
docker build --secret id=mysecret,src=mysecret.txt .
And inside your Dockerfile you can now access this secret
# syntax = docker/dockerfile:1.0-experimental
FROM alpine
# shows secret from default secret location:
RUN --mount=type=secret,id=mysecret cat /run/secrets/mysecret
# shows secret from custom secret location:
RUN --mount=type=secret,id=mysecret,dst=/foobar cat /foobar
More in-depth information about --secret available on Docker Docs
let jsonString = "{\"id\":123,\"Name\":\"Munish\"}"
Convert String to NSData
var data: NSData =jsonString.dataUsingEncoding(NSUTF8StringEncoding)!
var error: NSError?
Convert NSData to AnyObject
var jsonObject: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &error)
println("Error: \\(error)")
let id = (jsonObject as! NSDictionary)["id"] as! Int
let name = (jsonObject as! NSDictionary)["name"] as! String
println("Id: \\(id)")
println("Name: \\(name)")
I found this problem too. Because centos service depend on multi-user.target for none desktop Cenots 7.2. so I delete multi-user.target from my .service file. It had missed.
Bootstrap 4.0
Be aware of all migration changes from Bootstrap 3 to 4. On the table you now need to enable flex box by adding the class d-flex
, and drop the xs
to allow bootstrap to automatically detect the viewport.
<div class="container-fluid">
<table id="productSizes" class="table">
<thead>
<tr class="d-flex">
<th class="col-1">Size</th>
<th class="col-3">Bust</th>
<th class="col-3">Waist</th>
<th class="col-5">Hips</th>
</tr>
</thead>
<tbody>
<tr class="d-flex">
<td class="col-1">6</td>
<td class="col-3">79 - 81</td>
<td class="col-3">61 - 63</td>
<td class="col-5">89 - 91</td>
</tr>
<tr class="d-flex">
<td class="col-1">8</td>
<td class="col-3">84 - 86</td>
<td class="col-3">66 - 68</td>
<td class="col-5">94 - 96</td>
</tr>
</tbody>
</table>
Bootstrap 3.2
Table column width use the same layout as grids do; using col-[viewport]-[size]
. Remember the column sizes should total 12; 1 + 3 + 3 + 5 = 12
in this example.
<thead>
<tr>
<th class="col-xs-1">Size</th>
<th class="col-xs-3">Bust</th>
<th class="col-xs-3">Waist</th>
<th class="col-xs-5">Hips</th>
</tr>
</thead>
Remember to set the <th>
elements rather than the <td>
elements so it sets the whole column. Here is a working BOOTPLY.
Thanks to @Dan for reminding me to always work mobile view (col-xs-*
) first.
You, maybe the not the OP, but someone may have a directory called /var/run/docker.sock/
already due to how many times you hack and slash to get things right with docker (especially noobs). Delete that directory and try again.
This helped me on my way to getting it to work on Centos 7.
If this is for Cygwin, it installs "pip" as "pip2". Just create a softlink to "pip2" in the same location where "pip2" is installed.
For me it turned out that I had a @JsonManagedReferece
in one entity without a @JsonBackReference
in the other referenced entity. This caused the marshaller to throw an error.
Had the 407 error from Android Studio. Tried adding the proxy, but nothing happened. Found out that it was related to company certificate, so I exported the one from my browser and added it to Git.
Export From Web Browser
Internet Options > Content > Certificates > Export (Follow wizard, I chose format "Base 64 encoded X.509(.CER))
In Git Bash
git config --global http.sslCAInfo c:\Utilities\Certificates\my_certificate
The following page was useful https://blogs.msdn.microsoft.com/phkelley/2014/01/20/adding-a-corporate-or-self-signed-certificate-authority-to-git-exes-store/
To add the proxy, like the other threads I used
git config --global http.proxy proxy.company.net:8080
git config --global https.proxy proxy.company.net:8080
Just to complement the other answers as I don't think anyone mentioned this here: notifyDataSetChanged()
should be executed on the main thread (other notify<Something>
methods of RecyclerView.Adapter
as well, of course)
From what I gather, since you have the parsing procedures and the call to notifyDataSetChanged()
in the same block, either you're calling it from a worker thread, or you're doing JSON parsing on main thread (which is also a no-no as I'm sure you know). So the proper way would be:
protected void parseResponse(JSONArray response, String url) {
// insert dummy data for demo
// <yadda yadda yadda>
mBusinessAdapter = new BusinessAdapter(mBusinesses);
// or just use recyclerView.post() or [Fragment]getView().post()
// instead, but make sure views haven't been destroyed while you were
// parsing
new Handler(Looper.getMainLooper()).post(new Runnable() {
public void run() {
mBusinessAdapter.notifyDataSetChanged();
}
});
}
PS Weird thing is, I don't think you get any indications about the main thread thing from either IDE or run-time logs. This is just from my personal observations: if I do call notifyDataSetChanged()
from a worker thread, I don't get the obligatory Only the original thread that created a view hierarchy can touch its views message or anything like that - it just fails silently (and in my case one off-main-thread call can even prevent succeeding main-thread calls from functioning properly, probably because of some kind of race condition)
Moreover, neither the RecyclerView.Adapter api reference nor the relevant official dev guide explicitly mention the main thread requirement at the moment (the moment is 2017) and none of the Android Studio lint inspection rules seem to concern this issue either.
But, here is an explanation of this by the author himself
Also in case you had node installed before nvm check in your ~/.bash_profile to not have something like :
export PATH=/bin:/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin:$PATH
If you do have it, comment/remove it and nvm should start handling the default node version.
You can use the fuser
command, like:
fuser file_name
You will receive a list of processes using the file.
You can use different flags with it, in order to receive a more detailed output.
You can find more info in the fuser's Wikipedia article, or in the man
pages.
There's no real way to do this. As a result, things like mysqld_safe fail, and you can't install mysql-server in a Debian docker container without jumping through 40 hoops because.. well... it aborts if it's not root.
You can use USER, but you won't be able to apt-get install if you're not root.
So, the issue was that I was trying to inappropriately use @lazy, which caused my Business variable to essentially be a constant, and thusly uneditable. Also, instead of loading the local json, I'm now loading only the data returned from the API.
import UIKit
class BusinessTableViewController: UITableViewController {
var data: NSMutableData = NSMutableData()
var Business: NSMutableArray = NSMutableArray()
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.titleView = UIImageView(image: UIImage(named: "growler"))
tableView.registerClass(BeerTableViewCell.self, forCellReuseIdentifier: "cell")
tableView.separatorStyle = .None
fetchKimono()
}
override func numberOfSectionsInTableView(tableView: UITableView!) -> Int {
return Business.count
}
override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int {
if (Business.count > 0) {
let biz = Business[section] as NSDictionary
let beers = biz["results"] as NSArray
return beers.count
} else {
return 0;
}
}
override func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell? {
let cell = tableView!.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath!) as BeerTableViewCell
if let path = indexPath {
let biz = Business[path.section] as NSDictionary
let beers = biz["results"] as NSArray
let beer = beers[path.row] as NSDictionary
cell.titleLabel.text = beer["BeerName"] as String
} else {
cell.titleLabel.text = "Loading"
}
return cell
}
override func tableView(tableView: UITableView!, viewForHeaderInSection section: Int) -> UIView! {
let view = LocationHeaderView()
let biz = Business[section] as NSDictionary
if (Business.count > 0) {
let count = "\(Business.count)"
view.titleLabel.text = (biz["name"] as String).uppercaseString
}
return view
}
override func tableView(tableView: UITableView!, heightForHeaderInSection section: Int) -> CGFloat {
return 45
}
func fetchKimono() {
var urlPath = "names have been removed to protect the innocent"
var url: NSURL = NSURL(string: urlPath)
var request: NSURLRequest = NSURLRequest(URL: url)
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)
connection.start()
}
func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
// Recieved a new request, clear out the data object
self.data = NSMutableData()
}
func connection(connection: NSURLConnection!, didReceiveData data: NSData!) {
// Append the recieved chunk of data to our data object
self.data.appendData(data)
}
func connectionDidFinishLoading(connection: NSURLConnection!) {
// Request complete, self.data should now hold the resulting info
// Convert the retrieved data in to an object through JSON deserialization
var err: NSError
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
var results: NSDictionary = jsonResult["results"] as NSDictionary
var collection: NSArray = results["collection1"] as NSArray
if jsonResult.count>0 && collection.count>0 {
Business = jsonResult
tableView.reloadData()
}
}
}
You must always declare a lazy property as a variable (with the var keyword), because its initial value may not be retrieved until after instance initialization completes. Constant properties must always have a value before initialization completes, and therefore cannot be declared as lazy.
that is, for users of ngx_http_proxy_module
In addition to fastcgi
, the proxy
module also saves the request header in a temporary buffer.
So you may need also to increase the proxy_buffer_size
and the proxy_buffers
, or disable it totally (Please read the nginx documentation).
http {
proxy_buffer_size 128k;
proxy_buffers 4 256k;
proxy_busy_buffers_size 256k;
}
http {
proxy_buffering off;
}
For more information: Nginx proxy module documentation
;(function ($) {
$.fn.bootselect = function (options) {
this.each(function () {
var os = jQuery(this).find('option');
var parent = this.parentElement;
var css = jQuery(this).attr('class').split('input').join('btn').split('form-control').join('');
var vHtml = jQuery(this).find('option[value="' + jQuery(this).val() + '"]').html();
var html = '<div class="btn-group" role="group">' + '<button type="button" data-toggle="dropdown" value="1" class="btn btn-default ' + css + ' dropdown-toggle">' +
vHtml + '<span class="caret"></span>' + '</button>' + '<ul class="dropdown-menu">';
var i = 0;
while (i < os.length) {
html += '<li><a href="#" data-value="' + jQuery(os[i]).val() + '" html-attr="' + jQuery(os[i]).html() + '">' + jQuery(os[i]).html() + '</a></li>';
i++;
}
html += '</ul>' + '</div>';
var that = this;
jQuery(parent).append(html);
jQuery(parent).find('ul.dropdown-menu > li > a').on('click', function () {
jQuery(parent).find('button.btn').html(jQuery(this).html() + '<span class="caret"></span>');
jQuery(that).find('option[value="' + jQuery(this).attr('data-value') + '"]')[0].selected = true;
jQuery(that).trigger('change');
});
jQuery(this).hide();
});
};
}(jQuery));
jQuery('.bootstrap-select').bootselect();
this is a VB.NET version of the answer from dhanushka using EmguCV.
A few functions and structures in EmguCV need different consideration than the C# version with OpenCVSharp
Imports Emgu.CV
Imports Emgu.CV.Structure
Imports Emgu.CV.CvEnum
Imports Emgu.CV.Util
Dim input_file As String = "C:\your_input_image.png"
Dim large As Mat = New Mat(input_file)
Dim rgb As New Mat
Dim small As New Mat
Dim grad As New Mat
Dim bw As New Mat
Dim connected As New Mat
Dim morphanchor As New Point(0, 0)
'//downsample and use it for processing
CvInvoke.PyrDown(large, rgb)
CvInvoke.CvtColor(rgb, small, ColorConversion.Bgr2Gray)
'//morphological gradient
Dim morphKernel As Mat = CvInvoke.GetStructuringElement(ElementShape.Ellipse, New Size(3, 3), morphanchor)
CvInvoke.MorphologyEx(small, grad, MorphOp.Gradient, morphKernel, New Point(0, 0), 1, BorderType.Isolated, New MCvScalar(0))
'// binarize
CvInvoke.Threshold(grad, bw, 0, 255, ThresholdType.Binary Or ThresholdType.Otsu)
'// connect horizontally oriented regions
morphKernel = CvInvoke.GetStructuringElement(ElementShape.Rectangle, New Size(9, 1), morphanchor)
CvInvoke.MorphologyEx(bw, connected, MorphOp.Close, morphKernel, morphanchor, 1, BorderType.Isolated, New MCvScalar(0))
'// find contours
Dim mask As Mat = Mat.Zeros(bw.Size.Height, bw.Size.Width, DepthType.Cv8U, 1) '' MatType.CV_8UC1
Dim contours As New VectorOfVectorOfPoint
Dim hierarchy As New Mat
CvInvoke.FindContours(connected, contours, hierarchy, RetrType.Ccomp, ChainApproxMethod.ChainApproxSimple, Nothing)
'// filter contours
Dim idx As Integer
Dim rect As Rectangle
Dim maskROI As Mat
Dim r As Double
For Each hierarchyItem In hierarchy.GetData
rect = CvInvoke.BoundingRectangle(contours(idx))
maskROI = New Mat(mask, rect)
maskROI.SetTo(New MCvScalar(0, 0, 0))
'// fill the contour
CvInvoke.DrawContours(mask, contours, idx, New MCvScalar(255), -1)
'// ratio of non-zero pixels in the filled region
r = CvInvoke.CountNonZero(maskROI) / (rect.Width * rect.Height)
'/* assume at least 45% of the area Is filled if it contains text */
'/* constraints on region size */
'/* these two conditions alone are Not very robust. better to use something
'Like the number of significant peaks in a horizontal projection as a third condition */
If r > 0.45 AndAlso rect.Height > 8 AndAlso rect.Width > 8 Then
'draw green rectangle
CvInvoke.Rectangle(rgb, rect, New MCvScalar(0, 255, 0), 2)
End If
idx += 1
Next
rgb.Save(IO.Path.Combine(Application.StartupPath, "rgb.jpg"))
Use FileSaver.js
. It supports Chrome, Edge, Firefox, and IE 10+ (and probably IE < 10 with a few "polyfills" - see Note 4). FileSaver.js
implements the saveAs() FileSaver interface in browsers that do not natively support it:
https://github.com/eligrey/FileSaver.js
Minified version is really small at < 2.5KB, gzipped < 1.2KB.
Usage:
/* TODO: replace the blob content with your byte[] */
var blob = new Blob([yourBinaryDataAsAnArrayOrAsAString], {type: "application/octet-stream"});
var fileName = "myFileName.myExtension";
saveAs(blob, fileName);
You might need Blob.js in some browsers (see Note 3). Blob.js implements the W3C Blob interface in browsers that do not natively support it. It is a cross-browser implementation:
https://github.com/eligrey/Blob.js
Consider StreamSaver.js if you have files larger than blob's size limitations.
Complete example:
/* Two options_x000D_
* 1. Get FileSaver.js from here_x000D_
* https://github.com/eligrey/FileSaver.js/blob/master/FileSaver.min.js -->_x000D_
* <script src="FileSaver.min.js" />_x000D_
*_x000D_
* Or_x000D_
*_x000D_
* 2. If you want to support only modern browsers like Chrome, Edge, Firefox, etc., _x000D_
* then a simple implementation of saveAs function can be:_x000D_
*/_x000D_
function saveAs(blob, fileName) {_x000D_
var url = window.URL.createObjectURL(blob);_x000D_
_x000D_
var anchorElem = document.createElement("a");_x000D_
anchorElem.style = "display: none";_x000D_
anchorElem.href = url;_x000D_
anchorElem.download = fileName;_x000D_
_x000D_
document.body.appendChild(anchorElem);_x000D_
anchorElem.click();_x000D_
_x000D_
document.body.removeChild(anchorElem);_x000D_
_x000D_
// On Edge, revokeObjectURL should be called only after_x000D_
// a.click() has completed, atleast on EdgeHTML 15.15048_x000D_
setTimeout(function() {_x000D_
window.URL.revokeObjectURL(url);_x000D_
}, 1000);_x000D_
}_x000D_
_x000D_
(function() {_x000D_
// convert base64 string to byte array_x000D_
var byteCharacters = atob("R0lGODlhkwBYAPcAAAAAAAABGRMAAxUAFQAAJwAANAgwJSUAACQfDzIoFSMoLQIAQAAcQwAEYAAHfAARYwEQfhkPfxwXfQA9aigTezchdABBckAaAFwpAUIZflAre3pGHFpWVFBIf1ZbYWNcXGdnYnl3dAQXhwAXowkgigIllgIxnhkjhxktkRo4mwYzrC0Tgi4tiSQzpwBIkBJIsyxCmylQtDVivglSxBZu0SlYwS9vzDp94EcUg0wziWY0iFROlElcqkxrtW5OjWlKo31kmXp9hG9xrkty0ziG2jqQ42qek3CPqn6Qvk6I2FOZ41qn7mWNz2qZzGaV1nGOzHWY1Gqp3Wy93XOkx3W1x3i33G6z73nD+ZZIHL14KLB4N4FyWOsECesJFu0VCewUGvALCvACEfEcDfAcEusKJuoINuwYIuoXN+4jFPEjCvAgEPM3CfI5GfAxKuoRR+oaYustTus2cPRLE/NFJ/RMO/dfJ/VXNPVkNvFPTu5KcfdmQ/VuVvl5SPd4V/Nub4hVj49ol5RxoqZfl6x0mKp5q8Z+pu5NhuxXiu1YlvBdk/BZpu5pmvBsjfBilvR/jvF3lO5nq+1yre98ufBoqvBrtfB6p/B+uPF2yJiEc9aQMsSKQOibUvqKSPmEWPyfVfiQaOqkSfaqTfyhXvqwU+u7dfykZvqkdv+/bfy1fpGvvbiFnL+fjLGJqqekuYmTx4SqzJ2+2Yy36rGawrSwzpjG3YjB6ojG9YrU/5XI853U75bV/J3l/6PB6aDU76TZ+LHH6LHX7rDd+7Lh3KPl/bTo/bry/MGJm82VqsmkjtSptfWMj/KLsfu0je6vsNW1x/GIxPKXx/KX1ea8w/Wnx/Oo1/a3yPW42/S45fvFiv3IlP/anvzLp/fGu/3Xo/zZt//knP7iqP7qt//xpf/0uMTE3MPd1NXI3MXL5crS6cfe99fV6cXp/cj5/tbq+9j5/vbQy+bY5/bH6vbJ8vfV6ffY+f7px/3n2f/4yP742OPm8ef9//zp5vjn/f775/7+/gAAACwAAAAAkwBYAAAI/wD9CRxIsKDBgwgTKlzIsKHDhxAjSpxIsaLFixgzatzIsaPHjxD7YQrSyp09TCFSrQrxCqTLlzD9bUAAAMADfVkYwCIFoErMn0AvnlpAxR82A+tGWWgnLoCvoFCjOsxEopzRAUYwBFCQgEAvqWDDFgTVQJhRAVI2TUj3LUAusXDB4jsQxZ8WAMNCrW37NK7foN4u1HThD0sBWpoANPnL+GG/OV2gSUT24Yi/eltAcPAAooO+xqAVbkPT5VDo0zGzfemyqLE3a6hhmurSpRLjcGDI0ItdsROXSAn5dCGzTOC+d8j3gbzX5ky8g+BoTzq4706XL1/KzONdEBWXL3AS3v/5YubavU9fuKg/44jfQmbK4hdn+Jj2/ILRv0wv+MnLdezpweEed/i0YcYXkCQkB3h+tPEfgF3AsdtBzLSxGm1ftCHJQqhc54Y8B9UzxheJ8NfFgWakSF6EA57WTDN9kPdFJS+2ONAaKq6Whx88enFgeAYx892FJ66GyEHvvGggeMs0M01B9ajRRYkD1WMgF60JpAx5ZEgGWjZ44MHFdSkeSBsceIAoED5gqFgGbAMxQx4XlxjESRdcnFENcmmcGBlBfuDh4Ikq0kYGHoxUKSWVApmCnRsFCddlaEPSVuaFED7pDz5F5nGQJ9cJWFA/d1hSUCfYlSFQfdgRaqal6UH/epmUjRDUx3VHEtTPHp5SOuYyn5x4xiMv3jEmlgKNI+w1B/WTxhdnwLnQY2ZwEY1AeqgHRzN0/PiiMmh8x8Vu9YjRxX4CjYcgdwhhE6qNn8DBrD/5AXnQeF3ct1Ap1/VakB3YbThQgXEIVG4X1w7UyXUFs2tnvwq5+0XDBy38RZYMKQuejf7Yw4YZXVCjEHwFyQmyyA4TBPAXhiiUDcMJzfaFvwXdgWYbz/jTjxjgTTiQN2qYQca8DxV44KQpC7SyIi7DjJCcExeET7YAplcGNQvC8RxB3qS6XUTacHEgF7mmvHTTUT+Nnb06Ozi2emOWYeEZRAvUdXZfR/SJ2AdS/8zuymUf9HLaFGLnt3DkPTIQqTLSXRDQ2W0tETbYHSgru3eyjLbfJa9dpYEIG6QHdo4T5LHQdUfUjduas9vhxglJzLaJhKtGOEHdhKrm4gB3YapFdlznHLvhiB1tQtqEmpDFFL9umkH3hNGzQTF+8YZjzGi6uBgg58yuHH0nFM67CIH/xfP+OH9Q9LAXRHn3Du1NhuQCgY80dyZ/4caee58xocYSOgg+uOe7gWzDcwaRWMsOQocVLQI5bOBCggzSDzx8wQsTFEg4RnQ8h1nnVdchA8rucZ02+Iwg4xOaly4DOu8tbg4HogRC6uGfVx3oege5FbQ0VQ8Yts9hnxiUpf9qtapntYF+AxFFqE54qwPlYR772Mc2xpAiLqSOIPiwIG3OJC0ooQFAOVrNFbnTj/jEJ3U4MgPK/oUdmumMDUWCm6u6wDGDbMOMylhINli3IjO4MGkLqcMX7rc4B1nRIPboXdVUdLmNvExFGAMkQxZGHAHmYYXQ4xGPogGO1QBHkn/ZhhfIsDuL3IMLbjghKDECj3O40pWrjIk6XvkZj9hDCEKggAh26QAR9IAJsfzILXkpghj0RSPOYAEJdikCEjjTmczURTA3cgxmQlMEJbBFRlixAms+85vL3KUVpomRQOwSnMtUwTos8g4WnBOd8BTBCNxBzooA4p3oFAENKLL/Dx/g85neRCcEblDPifjzm/+UJz0jkgx35tMBSWDFCZqZTxWwo6AQYQVFwzkFh17zChG550YBKoJx9iMHIwVoCY6J0YVUk6K7TII/UEpSJRQNpSkNZy1WRdN8lgAXLWXIOyYKUIv2o5sklWlD7EHUfIrApsbxKDixqc2gJqQfOBipA4qwqRVMdQgNaWdOw2kD00kVodm0akL+MNJdfuYdbRWBUhVy1LGmc6ECEWs8S0AMtR4kGfjcJREEAliEPnUh9uipU1nqD8COVQQqwKtfBWIPXSJUBcEQCFsNO06F3BOe4ZzrQDQKWhHMYLIFEURKRVCDz5w0rlVFiEbtCtla/xLks/B0wBImAo98iJSZIrDBRTPSjqECd5c7hUgzElpSyjb1msNF0j+nCtJRaeCxIoiuQ2YhhF4el5cquIg9kJAD735Xt47RwWqzS9iEhjch/qTtaQ0C18fO1yHvQAFzmflTiwBiohv97n0bstzV3pcQCR0sQlQxXZLGliDVjGdzwxrfADvgBULo60WSEQHm8uAJE8EHUqfaWX8clKSMHViDAfoC2xJksxWVbEKSMWKSOgGvhOCBjlO8kPgi1AEqAMbifqDjsjLkpVNVZ15rvMwWI4SttBXBLQR41muWWCFQnuoLhquOCoNXxggRa1yVuo9Z6PK4okVklZdpZH8YY//MYWZykhFS4Io2JMsIjQE97cED814TstpFkgSY29lk4DTAMZ1xTncJVX+oF60aNgiMS8vVg4h0qiJ4MEJ8jNAX0FPMpR2wQaRRZUYLZBArDueVCXJdn0rzMgmttEHwYddr8riy603zQfBM0uE6o5u0dcCqB/IOyxq2zeasNWTBvNx4OtkfSL4mmE9d6yZPm8EVdfFBZovpRm/qzBJ+tq7WvEvtclvCw540QvepsxOH09u6UqxTdd3V1UZ2IY7FdAy0/drSrtQg7ibpsJsd6oLoNZ+vdsY7d9nmUT/XqcP2RyGYy+NxL9oB1TX4isVZkHxredq4zec8CXJuhI5guCH/L3dCLu3vYtD3rCpfCKoXPQJFl7bh/TC2YendbuwOg9WPZXd9ba2QgNtZ0ohWQaQTYo81L5PdzZI3QBse4XyS4NV/bfAusQ7X0ioVxrvUdEHsIeepQn0gdQ6nqBOCagmLneRah3rTH6sCbeuq7LvMeNUxPU69hn0hBAft0w0ycxEAORYI2YcrWJoBuq8zIdLQeps9PtWG73rRUh6I0aHZ3wqrAKiArzYJ0FsQbjjAASWIRTtkywIH3Hfo+RQ3ksjd5pCDU9gyx/zPN+V0EZiAGM3o5YVXP5Bk1OAgbxa8M3EfEXNUgJltnnk8bWB3i+dztzprfGkzTmfMDzftH8fH/w9igHWBBF8EuzBI8pUvAu43JNnLL7G6EWp5Na8X9GQXvAjKf5DAF3Ug0fZxCPFaIrB7BOF/8fR2COFYMFV3q7IDtFV/Y1dqniYQ3KBs/GcQhXV72OcPtpdn1eeBzBRo/tB1ysd8C+EMELhwIqBg/rAPUjd1IZhXMBdcaKdsCjgQbWdYx7R50KRn28ZM71UQ+6B9+gdvFMRp16RklOV01qYQARhOWLd3AoWEBfFoJCVuPrhM+6aB52SDllZt+pQQswAE3jVVpPeAUZaBBGF0pkUQJuhsCgF714R4mkdbTDhavRROoGcQUThVJQBmrLADZ4hpQzgQ87duCUGH4fRgIuOmfyXAhgLBctDkgHfob+UHf00Wgv1WWpDFC+qADuZwaNiVhwCYarvEY1gFZwURg9fUhV4YV0vnD+bkiS+ADurACoW4dQoBfk71XcFmA9NWD6mWTozVD+oVYBAge9SmfyIgAwbhDINmWEhIeZh2XNckgQVBicrHfrvkBFgmhsW0UC+FaMxIg8qGTZ3FD0r4bgfBVKKnbzM4EP1UjN64Sz1AgmOHU854eoUYTg4gjIqGirx0eoGFTVbYjN0IUMs4bc1yXfFoWIZHA/ngEGRnjxImVwwxWxFpWCPgclfVagtpeC9AfKIPwY3eGAM94JCehZGGFQOzuIj8uJDLhHrgKFRlh2k8xxCz8HwBFU4FaQOzwJIMQQ5mCFzXaHg28AsRUWbA9pNA2UtQ8HgNAQ8QuV6HdxHvkALudFwpAAMtEJMWMQgsAAPAyJVgxU47AANdCVwlAJaSuJEsAGDMBJYGiBH94Ap6uZdEiRGysJd7OY8S8Q6AqZe8kBHOUJiCiVqM2ZiO+ZgxERAAOw==");_x000D_
var byteNumbers = new Array(byteCharacters.length);_x000D_
for (var i = 0; i < byteCharacters.length; i++) {_x000D_
byteNumbers[i] = byteCharacters.charCodeAt(i);_x000D_
}_x000D_
var byteArray = new Uint8Array(byteNumbers);_x000D_
_x000D_
// now that we have the byte array, construct the blob from it_x000D_
var blob1 = new Blob([byteArray], {type: "application/octet-stream"});_x000D_
_x000D_
var fileName1 = "cool.gif";_x000D_
saveAs(blob1, fileName1);_x000D_
_x000D_
// saving text file_x000D_
var blob2 = new Blob(["cool"], {type: "text/plain"});_x000D_
var fileName2 = "cool.txt";_x000D_
saveAs(blob2, fileName2);_x000D_
})();
_x000D_
Tested on Chrome, Edge, Firefox, and IE 11 (use FileSaver.js
for supporting IE 11).
You can also save from a canvas
element. See https://github.com/eligrey/FileSaver.js#saving-a-canvas.
Demos: https://eligrey.com/demos/FileSaver.js/
Blog post by author of FileSaver.js
: http://eligrey.com/blog/post/saving-generated-files-on-the-client-side
Note 1: Browser support: https://github.com/eligrey/FileSaver.js#supported-browsers
Note 2: Failed to execute 'atob' on 'Window'
Note 3: Polyfill for browsers not supporting Blob: https://github.com/eligrey/Blob.js
See http://caniuse.com/#search=blob
Note 4: IE < 10 support (I've not tested this part):
https://github.com/eligrey/FileSaver.js#ie--10
https://github.com/eligrey/FileSaver.js/issues/56#issuecomment-30917476
Downloadify is a Flash-based polyfill for supporting IE6-9: https://github.com/dcneiner/downloadify (I don't recommend Flash-based solutions in general, though.)
Demo using Downloadify and FileSaver.js for supporting IE6-9 also: http://sheetjs.com/demos/table.html
Note 5: Creating a BLOB from a Base64 string in JavaScript
Note 6: FileSaver.js
examples: https://github.com/eligrey/FileSaver.js#examples
Are you getting errors, or just not sure where to start?
%pylab inline
import pandas as pd
import matplotlib.pyplot as plt
df2 = df.groupby(['Name', 'Abuse/NFF'])['Name'].count().unstack('Abuse/NFF').fillna(0)
df2[['abuse','nff']].plot(kind='bar', stacked=True)
Problem solved.
Just drop down status bar, touch Choose input method, then change to another input method, type the password again. And everything is OK.
So weird...
Solution from a Chinese BBS. Thanks for the answer's author and all above who try to provide a solution, thanks!
The body-parser
module only handles JSON and urlencoded form submissions, not multipart (which would be the case if you're uploading files).
For multipart, you'd need to use something like connect-busboy
or multer
or connect-multiparty
(multiparty/formidable is what was originally used in the express bodyParser middleware). Also FWIW, I'm working on an even higher level layer on top of busboy called reformed
. It comes with an Express middleware and can also be used separately.
To extend Arun's answer, for this to work in CentOS 7, I had to remove the "export" commands. So edit
/etc/sysconfig/docker
And add:
HTTP_PROXY="http://<proxy_host>:<proxy_port>"
HTTPS_PROXY="https://<proxy_host>:<proxy_port>"
http_proxy="${HTTP_PROXY}"
https_proxy="${HTTPS_PROXY}"
Then restart Docker:
sudo service docker restart
just import time
and add :
time.sleep(6)
somewhere in the for loop, to avoid sending too many request to the server in a short time. the number 6 means: 6 seconds. keep testing numbers starting from 1, until you reach the minimum seconds that will help to avoid the problem.
After exiting eclipse I moved .eclipse (found in the user's home directory) to .eclipse.old (just in case I may have had to undo). The error does not show up any more and my projects are working fine after restarting eclipse.
Caution: I have a simple setup and this may not be the best for environments with advanced settings.
I am posting this as a separate answer as previously listed methods did not work for me.
First of all, you should be aware of the fact that CUDA will not automagically make computations faster. On the one hand, because GPU programming is an art, and it can be very, very challenging to get it right. On the other hand, because GPUs are well-suited only for certain kinds of computations.
This may sound confusing, because you can basically compute anything on the GPU. The key point is, of course, whether you will achieve a good speedup or not. The most important classification here is whether a problem is task parallel or data parallel. The first one refers, roughly speaking, to problems where several threads are working on their own tasks, more or less independently. The second one refers to problems where many threads are all doing the same - but on different parts of the data.
The latter is the kind of problem that GPUs are good at: They have many cores, and all the cores do the same, but operate on different parts of the input data.
You mentioned that you have "simple math but with huge amount of data". Although this may sound like a perfectly data-parallel problem and thus like it was well-suited for a GPU, there is another aspect to consider: GPUs are ridiculously fast in terms of theoretical computational power (FLOPS, Floating Point Operations Per Second). But they are often throttled down by the memory bandwidth.
This leads to another classification of problems. Namely whether problems are memory bound or compute bound.
The first one refers to problems where the number of instructions that are done for each data element is low. For example, consider a parallel vector addition: You'll have to read two data elements, then perform a single addition, and then write the sum into the result vector. You will not see a speedup when doing this on the GPU, because the single addition does not compensate for the efforts of reading/writing the memory.
The second term, "compute bound", refers to problems where the number of instructions is high compared to the number of memory reads/writes. For example, consider a matrix multiplication: The number of instructions will be O(n^3) when n is the size of the matrix. In this case, one can expect that the GPU will outperform a CPU at a certain matrix size. Another example could be when many complex trigonometric computations (sine/cosine etc) are performed on "few" data elements.
As a rule of thumb: You can assume that reading/writing one data element from the "main" GPU memory has a latency of about 500 instructions....
Therefore, another key point for the performance of GPUs is data locality: If you have to read or write data (and in most cases, you will have to ;-)), then you should make sure that the data is kept as close as possible to the GPU cores. GPUs thus have certain memory areas (referred to as "local memory" or "shared memory") that usually is only a few KB in size, but particularly efficient for data that is about to be involved in a computation.
So to emphasize this again: GPU programming is an art, that is only remotely related to parallel programming on the CPU. Things like Threads in Java, with all the concurrency infrastructure like ThreadPoolExecutors
, ForkJoinPools
etc. might give the impression that you just have to split your work somehow and distribute it among several processors. On the GPU, you may encounter challenges on a much lower level: Occupancy, register pressure, shared memory pressure, memory coalescing ... just to name a few.
However, when you have a data-parallel, compute-bound problem to solve, the GPU is the way to go.
A general remark: Your specifically asked for CUDA. But I'd strongly recommend you to also have a look at OpenCL. It has several advantages. First of all, it's an vendor-independent, open industry standard, and there are implementations of OpenCL by AMD, Apple, Intel and NVIDIA. Additionally, there is a much broader support for OpenCL in the Java world. The only case where I'd rather settle for CUDA is when you want to use the CUDA runtime libraries, like CUFFT for FFT or CUBLAS for BLAS (Matrix/Vector operations). Although there are approaches for providing similar libraries for OpenCL, they can not directly be used from Java side, unless you create your own JNI bindings for these libraries.
You might also find it interesting to hear that in October 2012, the OpenJDK HotSpot group started the project "Sumatra": http://openjdk.java.net/projects/sumatra/ . The goal of this project is to provide GPU support directly in the JVM, with support from the JIT. The current status and first results can be seen in their mailing list at http://mail.openjdk.java.net/mailman/listinfo/sumatra-dev
However, a while ago, I collected some resources related to "Java on the GPU" in general. I'll summarize these again here, in no particular order.
(Disclaimer: I'm the author of http://jcuda.org/ and http://jocl.org/ )
https://github.com/aparapi/aparapi : An open-source library that is created and actively maintained by AMD. In a special "Kernel" class, one can override a specific method which should be executed in parallel. The byte code of this method is loaded at runtime using an own bytecode reader. The code is translated into OpenCL code, which is then compiled using the OpenCL compiler. The result can then be executed on the OpenCL device, which may be a GPU or a CPU. If the compilation into OpenCL is not possible (or no OpenCL is available), the code will still be executed in parallel, using a Thread Pool.
https://github.com/pcpratts/rootbeer1 : An open-source library for converting parts of Java into CUDA programs. It offers dedicated interfaces that may be implemented to indicate that a certain class should be executed on the GPU. In contrast to Aparapi, it tries to automatically serialize the "relevant" data (that is, the complete relevant part of the object graph!) into a representation that is suitable for the GPU.
https://code.google.com/archive/p/java-gpu/ : A library for translating annotated Java code (with some limitations) into CUDA code, which is then compiled into a library that executes the code on the GPU. The Library was developed in the context of a PhD thesis, which contains profound background information about the translation process.
https://github.com/ochafik/ScalaCL : Scala bindings for OpenCL. Allows special Scala collections to be processed in parallel with OpenCL. The functions that are called on the elements of the collections can be usual Scala functions (with some limitations) which are then translated into OpenCL kernels.
http://www.ateji.com/px/index.html : A language extension for Java that allows parallel constructs (e.g. parallel for loops, OpenMP style) which are then executed on the GPU with OpenCL. Unfortunately, this very promising project is no longer maintained.
http://www.habanero.rice.edu/Publications.html (JCUDA) : A library that can translate special Java Code (called JCUDA code) into Java- and CUDA-C code, which can then be compiled and executed on the GPU. However, the library does not seem to be publicly available.
https://www2.informatik.uni-erlangen.de/EN/research/JavaOpenMP/index.html : Java language extension for for OpenMP constructs, with a CUDA backend
https://github.com/ochafik/JavaCL : Java bindings for OpenCL: An object-oriented OpenCL library, based on auto-generated low-level bindings
http://jogamp.org/jocl/www/ : Java bindings for OpenCL: An object-oriented OpenCL library, based on auto-generated low-level bindings
http://www.lwjgl.org/ : Java bindings for OpenCL: Auto-generated low-level bindings and object-oriented convenience classes
http://jocl.org/ : Java bindings for OpenCL: Low-level bindings that are a 1:1 mapping of the original OpenCL API
http://jcuda.org/ : Java bindings for CUDA: Low-level bindings that are a 1:1 mapping of the original CUDA API
http://sourceforge.net/projects/jopencl/ : Java bindings for OpenCL. Seem to be no longer maintained since 2010
http://www.hoopoe-cloud.com/ : Java bindings for CUDA. Seem to be no longer maintained
In order to unit test code that relies on your database you need to setup a database or mock for each and every test.
I am working in an application that has a lot of tables with a lot of connections and some massive Linq blocks. These need testing. A simple grouping missed, or a join that results in more than 1 row will affect results.
To deal with this I have setup a heavy Unit Test Helper that is a lot of work to setup, but enables us to reliably mock the database in any state, and running 48 tests against 55 interconnected tables, with the entire database setup 48 times takes 4.7 seconds.
Here's how:
In the Db context class ensure each table class is set to virtual
public virtual DbSet<Branch> Branches { get; set; }
public virtual DbSet<Warehouse> Warehouses { get; set; }
In a UnitTestHelper class create a method to setup your database. Each table class is an optional parameter. If not supplied, it will be created through a Make method
internal static Db Bootstrap(bool onlyMockPassedTables = false, List<Branch> branches = null, List<Products> products = null, List<Warehouses> warehouses = null)
{
if (onlyMockPassedTables == false) {
branches ??= new List<Branch> { MakeBranch() };
warehouses ??= new List<Warehouse>{ MakeWarehouse() };
}
For each table class, each object in it is mapped to the other lists
branches?.ForEach(b => {
b.Warehouse = warehouses.FirstOrDefault(w => w.ID == b.WarehouseID);
});
warehouses?.ForEach(w => {
w.Branches = branches.Where(b => b.WarehouseID == w.ID);
});
And add it to the DbContext
var context = new Db(new DbContextOptionsBuilder<Db>().UseInMemoryDatabase(Guid.NewGuid().ToString()).Options);
context.Branches.AddRange(branches);
context.Warehouses.AddRange(warehouses);
context.SaveChanges();
return context;
}
Define a list of IDs to make is easier to reuse them and make sure joins are valid
internal const int BranchID = 1;
internal const int WarehouseID = 2;
Create a Make for each table to setup the most basic, but connected version it can be
internal static Branch MakeBranch(int id = BranchID, string code = "The branch", int warehouseId = WarehouseID) => new Branch { ID = id, Code = code, WarehouseID = warehouseId };
internal static Warehouse MakeWarehouse(int id = WarehouseID, string code = "B", string name = "My Big Warehouse") => new Warehouse { ID = id, Code = code, Name = name };
It's a lot of work, but it only needs doing once, and then your tests can be very focused because the rest of the database will be setup for it.
[Test]
[TestCase(new string [] {"ABC", "DEF"}, "ABC", ExpectedResult = 1)]
[TestCase(new string [] {"ABC", "BCD"}, "BC", ExpectedResult = 2)]
[TestCase(new string [] {"ABC"}, "EF", ExpectedResult = 0)]
[TestCase(new string[] { "ABC", "DEF" }, "abc", ExpectedResult = 1)]
public int Given_SearchingForBranchByName_Then_ReturnCount(string[] codesInDatabase, string searchString)
{
// Arrange
var branches = codesInDatabase.Select(x => UnitTestHelpers.MakeBranch(code: $"qqqq{x}qqq")).ToList();
var db = UnitTestHelpers.Bootstrap(branches: branches);
var service = new BranchService(db);
// Act
var result = service.SearchByName(searchString);
// Assert
return result.Count();
}
The function scipy.signal.find_peaks
, as its name suggests, is useful for this. But it's important to understand well its parameters width
, threshold
, distance
and above all prominence
to get a good peak extraction.
According to my tests and the documentation, the concept of prominence is "the useful concept" to keep the good peaks, and discard the noisy peaks.
What is (topographic) prominence? It is "the minimum height necessary to descend to get from the summit to any higher terrain", as it can be seen here:
The idea is:
The higher the prominence, the more "important" the peak is.
I had to change the js file, so to include "function()" at the beginning of it, and also "()" at the end line. That solved the problem
Dont know if this is good to anyone, but search all these dlls:
You find them in C:\Windows\assembly\GAC_MSIL\...
, and then put them in the references of your project.
For each of them say: local copy, and check for 32 or 64 bit solution.
With Ecma Script 2017 You can use async-await and while together to do that And while will not crash or lock the program even variable never be true
//First define some delay function which is called from async function_x000D_
function __delay__(timer) {_x000D_
return new Promise(resolve => {_x000D_
timer = timer || 2000;_x000D_
setTimeout(function () {_x000D_
resolve();_x000D_
}, timer);_x000D_
});_x000D_
};_x000D_
_x000D_
//Then Declare Some Variable Global or In Scope_x000D_
//Depends on you_x000D_
var flag = false;_x000D_
_x000D_
//And define what ever you want with async fuction_x000D_
async function some() {_x000D_
while (!flag)_x000D_
await __delay__(1000);_x000D_
_x000D_
//...code here because when Variable = true this function will_x000D_
};
_x000D_
Five options:
Use the free jsonutils web tool without installing anything.
If you have Web Essentials in Visual Studio, use Edit > Paste special > paste JSON as class.
Use the free jsonclassgenerator.exe
The web tool app.quicktype.io does not require installing anything.
The web tool json2csharp also does not require installing anything.
Pros and Cons:
jsonclassgenerator converts to PascalCase but the others do not.
app.quicktype.io has some logic to recognize dictionaries and handle JSON properties whose names are invalid c# identifiers.
Wrap the code within $(document).ready(function(){...........});
handler , also remove the ;
after if
$(document).ready(function(){
$('#purpose').on('change', function() {
if ( this.value == '1')
//.....................^.......
{
$("#business").show();
}
else
{
$("#business").hide();
}
});
});
In your JSP at line <form>
tag,
try this code
<form name="registrationform" action="Register" method="post">
You May Write this below code insdie your current java programme
System.setProperty("https.protocols", "TLSv1.1");
or
System.setProperty("http.proxyHost", "proxy.com");
System.setProperty("http.proxyPort", "911");
pip install pyqt5
for python3 for ubuntu
The type 'Domain.tblUser' is defined in an assembly that is not referenced. You must add a reference to assembly 'Domain, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
**Solved:**
Add reference of my domain library layer to my web app libary layer
Note: Make sure your references are correct according to you DI container
In our case we were getting UnmarshalException because a wrong Java package was specified in the following. The issue was resolved once the right package was in place:
@Bean
public Unmarshaller tmsUnmarshaller() {
final Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller();
jaxb2Marshaller
.setPackagesToScan("java.package.to.generated.java.classes.for.xsd");
return jaxb2Marshaller;
}
Your problem is this
<button type="button" value=" Send" class="btn btn-success" type="submit" id="submit" />
You've set the type twice. Your browser is only accepting the first, which is "button".
<button type="submit" value=" Send" class="btn btn-success" id="submit" />
Consider you've created a procedure like below.
CREATE OR REPLACE PROCEDURE GET_FULL_NAME like
(
FIRST_NAME IN VARCHAR2,
LAST_NAME IN VARCHAR2,
FULL_NAME OUT VARCHAR2
) IS
BEGIN
FULL_NAME:= FIRST_NAME || ' ' || LAST_NAME;
END GET_FULL_NAME;
In Oracle SQL Developer, you can run this procedure in two ways.
1. Using SQL Worksheet
Create a SQL Worksheet and write PL/SQL anonymous block like this and hit f5
DECLARE
FULL_NAME Varchar2(50);
BEGIN
GET_FULL_NAME('Foo', 'Bar', FULL_NAME);
Dbms_Output.Put_Line('Full name is: ' || FULL_NAME);
END;
2. Using GUI Controls
Expand Procedures
Right click on the procudure you've created and Click Run
In the pop-up window, Fill the parameters and Click OK.
Cheers!
I have updated the controller to:
.controller('BusinessCtrl',
function ($scope, $http, $location, Business, BusinessService, UserService, Photo) {
$scope.$watch('createBusinessForm.$valid', function(newVal) {
//$scope.valid = newVal;
$scope.informationStatus = true;
});
...
Read more: Dimension Table and Fact Table | Difference Between | Dimension Table vs Fact Table http://www.differencebetween.net/technology/hardware-technology/dimension-table-and-fact-table/#ixzz3SBp8kPzo
What if you need any database operation in SuperGirl
you would inject it again into SuperGirl
.
I think the main idea is using the same object reference in different classes. So what about this:
//There is no annotation about Spring in the abstract part.
abstract class SuperMan {
private final DatabaseService databaseService;
public SuperMan(DatabaseService databaseService) {
this.databaseService = databaseService;
}
abstract void Fly();
protected void doSuperPowerAction(Thing thing) {
//busy code
databaseService.save(thing);
}
}
@Component
public class SuperGirl extends SuperMan {
private final DatabaseService databaseService;
@Autowired
public SuperGirl (DatabaseService databaseService) {
super(databaseService);
this.databaseService = databaseService;
}
@Override
public void Fly() {
//busy code
}
public doSomethingSuperGirlDoes() {
//busy code
doSuperPowerAction(thing)
}
In my opinion, inject once run everywhere :)
So, there's no way that this works:
window.onload = function(){
<script language="JavaScript" src="http://jact.atdmt.com/jaction/JavaScriptTest"></script>
};
You can't freely drop HTML into the middle of javascript.
If you have jQuery, you can just use:
$.getScript("http://jact.atdmt.com/jaction/JavaScriptTest")
whenever you want. If you want to make sure the document has finished loading, you can do this:
$(document).ready(function() {
$.getScript("http://jact.atdmt.com/jaction/JavaScriptTest");
});
In plain javascript, you can load a script dynamically at any time you want to like this:
var tag = document.createElement("script");
tag.src = "http://jact.atdmt.com/jaction/JavaScriptTest";
document.getElementsByTagName("head")[0].appendChild(tag);
In SQL, this problem could be solved by several methods:
select * from df1 where exists (select * from df2 where df2.user_id = df1.user_id)
union all
select * from df2 where exists (select * from df1 where df1.user_id = df2.user_id)
or join and then unpivot (possible in SQL server)
select
df1.user_id,
c.rating
from df1
inner join df2 on df2.user_i = df1.user_id
outer apply (
select df1.rating union all
select df2.rating
) as c
Second one could be written in pandas with something like:
>>> df1 = pd.DataFrame({"user_id":[1,2,3], "rating":[10, 15, 20]})
>>> df2 = pd.DataFrame({"user_id":[3,4,5], "rating":[30, 35, 40]})
>>>
>>> df4 = df[['user_id', 'rating_1']].rename(columns={'rating_1':'rating'})
>>> df = pd.merge(df1, df2, on='user_id', suffixes=['_1', '_2'])
>>> df3 = df[['user_id', 'rating_1']].rename(columns={'rating_1':'rating'})
>>> df4 = df[['user_id', 'rating_2']].rename(columns={'rating_2':'rating'})
>>> pd.concat([df3, df4], axis=0)
user_id rating
0 3 20
0 3 30
I think the problem is with the way you designed your data. To me in terms of semantics, it just doesn't make sense. What exactly is steps for?
Does it store the information of one company?
If that's the case steps should be an object (see KayakDave's answer) and each "step" should be an object property.
Does it store the information of multiple companies?
If that's the case, steps should be an array of objects.
$scope.steps=[{companyName: true, businessType: true},{companyName: false}]
In either case you can easily iterate through the data with one (two for 2nd case) ng-repeats.
Think of a GrantedAuthority as being a "permission" or a "right". Those "permissions" are (normally) expressed as strings (with the getAuthority()
method). Those strings let you identify the permissions and let your voters decide if they grant access to something.
You can grant different GrantedAuthoritys (permissions) to users by putting them into the security context. You normally do that by implementing your own UserDetailsService that returns a UserDetails implementation that returns the needed GrantedAuthorities.
Roles (as they are used in many examples) are just "permissions" with a naming convention that says that a role is a GrantedAuthority that starts with the prefix ROLE_
. There's nothing more. A role is just a GrantedAuthority - a "permission" - a "right". You see a lot of places in spring security where the role with its ROLE_
prefix is handled specially as e.g. in the RoleVoter, where the ROLE_
prefix is used as a default. This allows you to provide the role names withtout the ROLE_
prefix. Prior to Spring security 4, this special handling of "roles" has not been followed very consistently and authorities and roles were often treated the same (as you e.g. can see in the implementation of the hasAuthority()
method in SecurityExpressionRoot - which simply calls hasRole()
). With Spring Security 4, the treatment of roles is more consistent and code that deals with "roles" (like the RoleVoter
, the hasRole
expression etc.) always adds the ROLE_
prefix for you. So hasAuthority('ROLE_ADMIN')
means the the same as hasRole('ADMIN')
because the ROLE_
prefix gets added automatically. See the spring security 3 to 4 migration guide for futher information.
But still: a role is just an authority with a special ROLE_
prefix. So in Spring security 3 @PreAuthorize("hasRole('ROLE_XYZ')")
is the same as @PreAuthorize("hasAuthority('ROLE_XYZ')")
and in Spring security 4 @PreAuthorize("hasRole('XYZ')")
is the same as @PreAuthorize("hasAuthority('ROLE_XYZ')")
.
Regarding your use case:
Users have roles and roles can perform certain operations.
You could end up in GrantedAuthorities
for the roles a user belongs to and the operations a role can perform. The GrantedAuthorities
for the roles have the prefix ROLE_
and the operations have the prefix OP_
. An example for operation authorities could be OP_DELETE_ACCOUNT
, OP_CREATE_USER
, OP_RUN_BATCH_JOB
etc. Roles can be ROLE_ADMIN
, ROLE_USER
, ROLE_OWNER
etc.
You could end up having your entities implement GrantedAuthority
like in this (pseudo-code) example:
@Entity
class Role implements GrantedAuthority {
@Id
private String id;
@ManyToMany
private final List<Operation> allowedOperations = new ArrayList<>();
@Override
public String getAuthority() {
return id;
}
public Collection<GrantedAuthority> getAllowedOperations() {
return allowedOperations;
}
}
@Entity
class User {
@Id
private String id;
@ManyToMany
private final List<Role> roles = new ArrayList<>();
public Collection<Role> getRoles() {
return roles;
}
}
@Entity
class Operation implements GrantedAuthority {
@Id
private String id;
@Override
public String getAuthority() {
return id;
}
}
The ids of the roles and operations you create in your database would be the GrantedAuthority representation, e.g. ROLE_ADMIN
, OP_DELETE_ACCOUNT
etc. When a user is authenticated, make sure that all GrantedAuthorities of all its roles and the corresponding operations are returned from the UserDetails.getAuthorities() method.
Example:
The admin role with id ROLE_ADMIN
has the operations OP_DELETE_ACCOUNT
, OP_READ_ACCOUNT
, OP_RUN_BATCH_JOB
assigned to it.
The user role with id ROLE_USER
has the operation OP_READ_ACCOUNT
.
If an admin logs in the resulting security context will have the GrantedAuthorities:
ROLE_ADMIN
, OP_DELETE_ACCOUNT
, OP_READ_ACCOUNT
, OP_RUN_BATCH_JOB
If a user logs it, it will have:
ROLE_USER
, OP_READ_ACCOUNT
The UserDetailsService would take care to collect all roles and all operations of those roles and make them available by the method getAuthorities() in the returned UserDetails instance.
Bootstrap 3
Try this. Simple solution with no dependencies.
$('[data-toggle="collapse"]').click(function() {
$('.collapse.in').collapse('hide')
});
_x000D_
The process of assembling tree nodes is similar to the process of assembling lists. We have a constructor for tree nodes that initializes the instance variables.
public Tree (Object cargo, Tree left, Tree right) {
this.cargo = cargo;
this.left = left;
this.right = right;
}
We allocate the child nodes first:
Tree left = new Tree (new Integer(2), null, null);
Tree right = new Tree (new Integer(3), null, null);
We can create the parent node and link it to the children at the same time:
Tree tree = new Tree (new Integer(1), left, right);
from sklearn import model_selection
test_size = 0.33
seed = 7
X_train, X_test, y_train, y_test = model_selection.train_test_split(feature_vectors, y, test_size=test_size, random_state=seed)
from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score, classification_report, confusion_matrix
model = LogisticRegression()
model.fit(X_train, y_train)
result = model.score(X_test, y_test)
print("Accuracy: %.3f%%" % (result*100.0))
y_pred = model.predict(X_test)
print("F1 Score: ", f1_score(y_test, y_pred, average="macro"))
print("Precision Score: ", precision_score(y_test, y_pred, average="macro"))
print("Recall Score: ", recall_score(y_test, y_pred, average="macro"))
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics import confusion_matrix
def cm_analysis(y_true, y_pred, labels, ymap=None, figsize=(10,10)):
"""
Generate matrix plot of confusion matrix with pretty annotations.
The plot image is saved to disk.
args:
y_true: true label of the data, with shape (nsamples,)
y_pred: prediction of the data, with shape (nsamples,)
filename: filename of figure file to save
labels: string array, name the order of class labels in the confusion matrix.
use `clf.classes_` if using scikit-learn models.
with shape (nclass,).
ymap: dict: any -> string, length == nclass.
if not None, map the labels & ys to more understandable strings.
Caution: original y_true, y_pred and labels must align.
figsize: the size of the figure plotted.
"""
if ymap is not None:
y_pred = [ymap[yi] for yi in y_pred]
y_true = [ymap[yi] for yi in y_true]
labels = [ymap[yi] for yi in labels]
cm = confusion_matrix(y_true, y_pred, labels=labels)
cm_sum = np.sum(cm, axis=1, keepdims=True)
cm_perc = cm / cm_sum.astype(float) * 100
annot = np.empty_like(cm).astype(str)
nrows, ncols = cm.shape
for i in range(nrows):
for j in range(ncols):
c = cm[i, j]
p = cm_perc[i, j]
if i == j:
s = cm_sum[i]
annot[i, j] = '%.1f%%\n%d/%d' % (p, c, s)
elif c == 0:
annot[i, j] = ''
else:
annot[i, j] = '%.1f%%\n%d' % (p, c)
cm = pd.DataFrame(cm, index=labels, columns=labels)
cm.index.name = 'Actual'
cm.columns.name = 'Predicted'
fig, ax = plt.subplots(figsize=figsize)
sns.heatmap(cm, annot=annot, fmt='', ax=ax)
#plt.savefig(filename)
plt.show()
cm_analysis(y_test, y_pred, model.classes_, ymap=None, figsize=(10,10))
using https://gist.github.com/hitvoice/36cf44689065ca9b927431546381a3f7
Note that if you use rocket_r
it will reverse the colors and somehow it looks more natural and better such as below:
Even without pop
the list we can do with set_index
pd.DataFrame(table).T.set_index(0).T
Out[11]:
0 Heading1 Heading2
1 1 2
2 3 4
Update from_records
table = [['Heading1', 'Heading2'], [1 , 2], [3, 4]]
pd.DataFrame.from_records(table[1:],columns=table[0])
Out[58]:
Heading1 Heading2
0 1 2
1 3 4
I came across a similar problem with a meta tag. In the designer.cs
, the control was defined as:
protected global::System.Web.UI.HtmlControl.HtmlGenericControl metatag;
I had to move the definition to the .aspx.cs
file and define as:
protected global::System.Web.UI.HtmlControl.HtmlMeta metatag;
First of all use
mysqli_connect($dbhost,$dbuser,$dbpass,$dbname)
Second - put mysqli_
everywhere instead of mysql_
Third - use this
$sql = "UPDATE anstalld SET mandag = '.$mandag.', tisdag = '.$tisdag.', onsdag = '.$onsdag.', torsdag = '.$torsdag.', fredag = '.$fredag.' WHERE namn = '.$namn.'";
$retval = mysqli_query( $conn, $sql ); //execute your query
if Your data is being updated in your database but not in your table its because when you will click on update button, the request is made to the same file. It first selects the data from the database when it is not updated prints it in the table and then update it according to the flow. If you have to update it as you click on update button then put this section
<?php
if(isset($_POST['update']))
{
$namn = $_POST['namnid'];
$mandag = $_POST['mandagid'];
$tisdag = $_POST['tisdagid'];
$onsdag = $_POST['onsdagid'];
$torsdag = $_POST['torsdagid'];
$fredag = $_POST['fredagid'];
$sql = mysql_query("UPDATE anstalld SET mandag = '$mandag', tisdag = '$tisdag', onsdag = '$onsdag', torsdag = '$torsdag', fredag = '$fredag' WHERE namn = '$namn'");
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";
}
?>`
after connecting with database.
In your case, the first value to insert must be NULL, because it's AUTO_INCREMENT.
In case anyone needs to try and merge two dataframes together on the index (instead of another column), this also works!
T1 and T2 are dataframes that have the same indices
import pandas as pd
T1 = pd.merge(T1, T2, on=T1.index, how='outer')
P.S. I had to use merge because append would fill NaNs in unnecessarily.
I recommend to use bellow formula suggested on Apache:
MaxClients = (total RAM - RAM for OS - RAM for external programs) / (RAM per httpd process)
Find my script here which is running on Rhel 6.7. you can made change according to your OS.
#!/bin/bash
echo "HostName=`hostname`"
#Formula
#MaxClients . (RAM - size_all_other_processes)/(size_apache_process)
total_httpd_processes_size=`ps -ylC httpd --sort:rss | awk '{ sum += $9 } END { print sum }'`
#echo "total_httpd_processes_size=$total_httpd_processes_size"
total_http_processes_count=`ps -ylC httpd --sort:rss | wc -l`
echo "total_http_processes_count=$total_http_processes_count"
AVG_httpd_process_size=$(expr $total_httpd_processes_size / $total_http_processes_count)
echo "AVG_httpd_process_size=$AVG_httpd_process_size"
total_httpd_process_size_MB=$(expr $AVG_httpd_process_size / 1024)
echo "total_httpd_process_size_MB=$total_httpd_process_size_MB"
total_pttpd_used_size=$(expr $total_httpd_processes_size / 1024)
echo "total_pttpd_used_size=$total_pttpd_used_size"
total_RAM_size=`free -m |grep Mem |awk '{print $2}'`
echo "total_RAM_size=$total_RAM_size"
total_used_size=`free -m |grep Mem |awk '{print $3}'`
echo "total_used_size=$total_used_size"
size_all_other_processes=$(expr $total_used_size - $total_pttpd_used_size)
echo "size_all_other_processes=$size_all_other_processes"
remaining_memory=$(($total_RAM_size - $size_all_other_processes))
echo "remaining_memory=$remaining_memory"
MaxClients=$((($total_RAM_size - $size_all_other_processes) / $total_httpd_process_size_MB))
echo "MaxClients=$MaxClients"
exit
put .gitignore in your main catalog
git status (you will see which files you can commit)
git add -A
git commit -m "message"
git push
You should be using it like so
<?php
$dbhost = 'localhost';
$dbname = 'pdo';
$dbusername = 'root';
$dbpassword = '845625';
$link = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbusername, $dbpassword);
$statement = $link->prepare('INSERT INTO testtable (name, lastname, age)
VALUES (:fname, :sname, :age)');
$statement->execute([
'fname' => 'Bob',
'sname' => 'Desaunois',
'age' => '18',
]);
Prepared statements are used to sanitize your input, and to do that you can use :foo
without any single quotes within the SQL to bind variables, and then in the execute()
function you pass in an associative array of the variables you defined in the SQL statement.
You may also use ?
instead of :foo
and then pass in an array of just the values to input like so;
$statement = $link->prepare('INSERT INTO testtable (name, lastname, age)
VALUES (?, ?, ?)');
$statement->execute(['Bob', 'Desaunois', '18']);
Both ways have their advantages and disadvantages. I personally prefer to bind the parameter names as it's easier for me to read.
curl
sends POST requests with the default content type of application/x-www-form-urlencoded
. If you want to send a JSON request, you will have to specify the correct content type header:
$ curl -vX POST http://server/api/v1/places.json -d @testplace.json \
--header "Content-Type: application/json"
But that will only work if the server accepts json input. The .json
at the end of the url may only indicate that the output is json, it doesn't necessarily mean that it also will handle json input. The API documentation should give you a hint on whether it does or not.
The reason you get a 401
and not some other error is probably because the server can't extract the auth_token
from your request.
you can use transition in css3:
.carousel-fade .carousel-inner .item {_x000D_
-webkit-transition-property: opacity;_x000D_
transition-property: opacity;_x000D_
}_x000D_
.carousel-fade .carousel-inner .item,_x000D_
.carousel-fade .carousel-inner .active.left,_x000D_
.carousel-fade .carousel-inner .active.right {_x000D_
opacity: 0;_x000D_
}_x000D_
.carousel-fade .carousel-inner .active,_x000D_
.carousel-fade .carousel-inner .next.left,_x000D_
.carousel-fade .carousel-inner .prev.right {_x000D_
opacity: 1;_x000D_
}_x000D_
.carousel-fade .carousel-inner .next,_x000D_
.carousel-fade .carousel-inner .prev,_x000D_
.carousel-fade .carousel-inner .active.left,_x000D_
.carousel-fade .carousel-inner .active.right {_x000D_
left: 0;_x000D_
-webkit-transform: translate3d(0, 0, 0);_x000D_
transform: translate3d(0, 0, 0);_x000D_
}_x000D_
.carousel-fade .carousel-control {_x000D_
z-index: 2;_x000D_
}
_x000D_
Given a data setup like this:
The formula in cell D2 and copied down is:
=INDEX($B$2:$B$28,MATCH(1,INDEX(($A$2:$A$28=LARGE($A$2:$A$28,ROWS(D$1:D1)))*(COUNTIF(D$1:D1,$B$2:$B$28)=0),),0))
This formula will work even if there are tied OPS scores among players.
At first simply uninstall wifi drivers and softwares just keep wifi drivers + from device manager....network adapters...remove all virtual connections
then
Press the Windows + R key combination to bring up a run box, type ncpa.cpl and hit enter.
netsh wlan set hostednetwork mode=allow ssid=”How-To Geek” key=”Pa$$w0rd”
netsh wlan start hostednetwork
netsh wlan show hostednetwork
its working for me and on others PC.
@model AdventureWork.CRUD.WebApp4.Models.EmployeeViewModel
@{
ViewBag.Title = "Detalle";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Ingresar Usuario</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Employee.PersonType, labelText: "Tipo de Persona", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.Employee.PersonType, new List<SelectListItem>
{
new SelectListItem{ Text= "SC", Value = "SC" },
new SelectListItem{ Text= "VC", Value = "VC" },
new SelectListItem{ Text= "IN", Value = "IN" },
new SelectListItem{ Text= "EM", Value = "EM" },
new SelectListItem{ Text= "SP", Value = "SP" },
}, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Employee.PersonType, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.EmployeeGender, labelText: "Genero", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.Employee.EmployeeGender, new List<SelectListItem>
{
new SelectListItem{ Text= "Masculino", Value = "M" },
new SelectListItem{ Text= "Femenino", Value = "F" }
}, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Employee.EmployeeGender, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.PersonTitle, labelText: "Titulo", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Employee.PersonTitle, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Employee.PersonTitle, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.PersonFirstName, labelText: "Primer Nombre", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Employee.PersonFirstName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Employee.PersonFirstName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.PersonMiddleName, labelText: "Segundo Nombre", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Employee.PersonMiddleName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Employee.PersonMiddleName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.PersonLastName, labelText: "Apellido", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Employee.PersonLastName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Employee.PersonLastName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.PersonSuffix, labelText: "Sufijo", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Employee.PersonSuffix, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Employee.PersonSuffix, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.DepartmentID, labelText: "Departamento", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.Employee.DepartmentID, new SelectList(Model.ListDepartment, "DepartmentID", "DepartmentName"), htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Employee.DepartmentID, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.EmployeeMaritalStatus, labelText: "Estado Civil", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.Employee.EmployeeMaritalStatus, new List<SelectListItem>
{
new SelectListItem{ Text= "Soltero", Value = "S" },
new SelectListItem{ Text= "Casado", Value = "M" }
}, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Employee.EmployeeMaritalStatus, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.ShiftId, labelText: "Turno", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.Employee.ShiftId, new SelectList(Model.ListShift, "ShiftId", "ShiftName"), htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Employee.ShiftId, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.EmployeeLoginId, labelText: "Login", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Employee.EmployeeLoginId, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Employee.EmployeeLoginId, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.EmployeeNationalIDNumber, labelText: "Identificacion Nacional", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Employee.EmployeeNationalIDNumber, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Employee.EmployeeNationalIDNumber, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.EmployeeJobTitle, labelText: "Cargo", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Employee.EmployeeJobTitle, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Employee.EmployeeJobTitle, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.EmployeeBirthDate, labelText: "Fecha Nacimiento", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Employee.EmployeeBirthDate, new { htmlAttributes = new { @class = "form-control datepicker" } })
@Html.ValidationMessageFor(model => model.Employee.EmployeeBirthDate, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.EmployeeSalariedFlag, labelText: "Asalariado", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Employee.EmployeeSalariedFlag, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Employee.EmployeeSalariedFlag, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Guardar" class="btn btn-default" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10" style="color:green">
@ViewBag.Message
</div>
<div class="col-md-offset-2 col-md-10" style="color:red">
@ViewBag.ErrorMessage
</div>
</div>
</div>
}
I found that I have ticked "Run whether user is logged on or not" and it returns a silent failure.
When I changed tick "Run only when user is logged on" instead it works for me.
I had the exact same issue and nothing helped.
eventually I saw that I had a mismatch in my namespaces of the unit project and the unit test project.
The namespace of my unit project is unit.project and the test project was named unit.project.tests but the default namespace of the test was the same as the unit, both was unit.project.
Once I've updated the namespaces to be different (one namespace for each project) everything worked!
Try this :
$('select[name^="salesrep"] option[value="Bruce Jones"]').attr("selected","selected");
Just replace option[value="Bruce Jones"]
by option[value=result[0]]
And before selecting a new option, you might want to "unselect" the previous :
$('select[name^="salesrep"] option:selected').attr("selected",null);
You may want to read this too : jQuery get specific option tag text
Edit: Using jQuery Mobile, this link may provide a good solution : jquery mobile - set select/option values
You need to wrap the text in a div
element and include the absolutely positioned element inside of it.
<div class="container">
<div class="inner">
<div class="full-height"></div>
[Your text here]
</div>
</div>
Css:
.inner: { position: relative; height: auto; }
.full-height: { height: 100%; }
Setting the inner div's position to relative
makes the absolutely position elements inside of it base their position and height on it rather than on the .container
div, which has a fixed height. Without the inner, relatively positioned div
, the .full-height
div will always calculate its dimensions and position based on .container
.
* {_x000D_
box-sizing: border-box;_x000D_
}_x000D_
_x000D_
.container {_x000D_
position: relative;_x000D_
border: solid 1px red;_x000D_
height: 256px;_x000D_
width: 256px;_x000D_
overflow: auto;_x000D_
float: left;_x000D_
margin-right: 16px;_x000D_
}_x000D_
_x000D_
.inner {_x000D_
position: relative;_x000D_
height: auto;_x000D_
}_x000D_
_x000D_
.full-height {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
right: 128px;_x000D_
bottom: 0;_x000D_
height: 100%;_x000D_
background: blue;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="full-height">_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div class="container">_x000D_
<div class="inner">_x000D_
<div class="full-height">_x000D_
</div>_x000D_
_x000D_
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur mollitia maxime facere quae cumque perferendis cum atque quia repellendus rerum eaque quod quibusdam incidunt blanditiis possimus temporibus reiciendis deserunt sequi eveniet necessitatibus_x000D_
maiores quas assumenda voluptate qui odio laboriosam totam repudiandae? Doloremque dignissimos voluptatibus eveniet rem quasi minus ex cumque esse culpa cupiditate cum architecto! Facilis deleniti unde suscipit minima obcaecati vero ea soluta odio_x000D_
cupiditate placeat vitae nesciunt quis alias dolorum nemo sint facere. Deleniti itaque incidunt eligendi qui nemo corporis ducimus beatae consequatur est iusto dolorum consequuntur vero debitis saepe voluptatem impedit sint ea numquam quia voluptate_x000D_
quidem._x000D_
</div>_x000D_
</div>
_x000D_
You can implement this way
$resource('http://localhost\\:3000/realmen/:entryId', {entryId: '@entryId'}, {
UPDATE: {method: 'PUT', url: 'http://localhost\\:3000/realmen/:entryId' },
ACTION: {method: 'PUT', url: 'http://localhost\\:3000/realmen/:entryId/action' }
})
RealMen.query() //GET /realmen/
RealMen.save({entryId: 1},{post data}) // POST /realmen/1
RealMen.delete({entryId: 1}) //DELETE /realmen/1
//any optional method
RealMen.UPDATE({entryId:1}, {post data}) // PUT /realmen/1
//query string
RealMen.query({name:'john'}) //GET /realmen?name=john
Documentation: https://docs.angularjs.org/api/ngResource/service/$resource
Hope it helps
Put the following code into head section in your web page programming.
<head>
<style>.carousel-inner > .item > img { width:100%; height:570px; } </style>
</head>
I don't think it's the right way to use angular. If a framework method doesnt exist, don't create it! This means the framework (here angular) doesnt work this way.
With angular you should not manipulate DOM like this (the jquery way), but use angular helper such as
<div ng-show="isLoading" class="loader"></div>
Or create your own directive (your own DOM component) in order to have full control on it.
BTW, you can see here http://caniuse.com/#search=queryselector querySelector is well supported and so can be use safely.
I have discovered that you cannot have conditionals outside of the stored procedure in mysql. This is why the syntax error. As soon as I put the code that I needed between
BEGIN
SELECT MONTH(CURDATE()) INTO @curmonth;
SELECT MONTHNAME(CURDATE()) INTO @curmonthname;
SELECT DAY(LAST_DAY(CURDATE())) INTO @totaldays;
SELECT FIRST_DAY(CURDATE()) INTO @checkweekday;
SELECT DAY(@checkweekday) INTO @checkday;
SET @daycount = 0;
SET @workdays = 0;
WHILE(@daycount < @totaldays) DO
IF (WEEKDAY(@checkweekday) < 5) THEN
SET @workdays = @workdays+1;
END IF;
SET @daycount = @daycount+1;
SELECT ADDDATE(@checkweekday, INTERVAL 1 DAY) INTO @checkweekday;
END WHILE;
END
Just for others:
If you are not sure how to create a routine in phpmyadmin you can put this in the SQL query
delimiter ;;
drop procedure if exists test2;;
create procedure test2()
begin
select ‘Hello World’;
end
;;
Run the query. This will create a stored procedure or stored routine named test2. Now go to the routines tab and edit the stored procedure to be what you want. I also suggest reading http://net.tutsplus.com/tutorials/an-introduction-to-stored-procedures/ if you are beginning with stored procedures.
The first_day function you need is: How to get first day of every corresponding month in mysql?
Showing the Procedure is working Simply add the following line below END WHILE and above END
SELECT @curmonth,@curmonthname,@totaldays,@daycount,@workdays,@checkweekday,@checkday;
Then use the following code in the SQL Query Window.
call test2 /* or whatever you changed the name of the stored procedure to */
NOTE: If you use this please keep in mind that this code does not take in to account nationally observed holidays (or any holidays for that matter).
Suppress the @JoinColumn(name="categoria")
on the ID field of the Categoria
class and I think it will work.
I'm hoping someone can provide some concrete examples of best use cases for each.
Use Retrofit if you are communicating with a Web service. Use the peer library Picasso if you are downloading images. Use OkHTTP if you need to do HTTP operations that lie outside of Retrofit/Picasso.
Volley roughly competes with Retrofit + Picasso. On the plus side, it is one library. On the minus side, it is one undocumented, an unsupported, "throw the code over the wall and do an I|O presentation on it" library.
EDIT - Volley is now officially supported by Google. Kindly refer Google Developer Guide
From what I've read, seems like OkHTTP is the most robust of the 3
Retrofit uses OkHTTP automatically if available. There is a Gist from Jake Wharton that connects Volley to OkHTTP.
and could handle the requirements of this project (mentioned above).
Probably you will use none of them for "streaming download of audio and video", by the conventional definition of "streaming". Instead, Android's media framework will handle those HTTP requests for you.
That being said, if you are going to attempt to do your own HTTP-based streaming, OkHTTP should handle that scenario; I don't recall how well Volley would handle that scenario. Neither Retrofit nor Picasso are designed for that.
Based on @Arun P Johny this is how you do it for an input:
<input type="button" class="btEdit" id="myButton1">
This is how I got it in jQuery:
$(document).on('click', "input.btEdit", function () {
var id = this.id;
console.log(id);
});
This will log on the console: myButton1. As @Arun said you need to add the event dinamically, but in my case you don't need to call the parent first.
UPDATE
Though it would be better to say:
$(document).on('click', "input.btEdit", function () {
var id = $(this).id;
console.log(id);
});
Since this is JQuery's syntax, even though both will work.
Here is a list of examples for sending cookies - https://github.com/andriichuk/php-curl-cookbook#cookies
$curlHandler = curl_init();
curl_setopt_array($curlHandler, [
CURLOPT_URL => 'https://httpbin.org/cookies',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_COOKIEFILE => $cookieFile,
CURLOPT_COOKIE => 'foo=bar;baz=foo',
/**
* Or set header
* CURLOPT_HTTPHEADER => [
'Cookie: foo=bar;baz=foo',
]
*/
]);
$response = curl_exec($curlHandler);
curl_close($curlHandler);
echo $response;
(Update: overlooked a fault in the matter, I have corrected)
(Update2: I wrote from memory the code screwed up, repaired it)
(Update3: check on SQLFiddle)
create table Derived_Values
(
BusinessUnit nvarchar(100) not null
,Questions nvarchar(100) not null
,Answer nvarchar(100)
)
go
ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);
create table Derived_Values_Test
(
BusinessUnit nvarchar(150)
,Questions nvarchar(100)
,Answer nvarchar(100)
)
go
CREATE TRIGGER trgAfterUpdate ON [Derived_Values]
FOR UPDATE
AS
begin
declare @BusinessUnit nvarchar(50)
set @BusinessUnit = 'Updated Record -- After Update Trigger.'
insert into
[Derived_Values_Test]
--(BusinessUnit,Questions, Answer)
SELECT
@BusinessUnit + i.BusinessUnit, i.Questions, i.Answer
FROM
inserted i
inner join deleted d on i.BusinessUnit = d.BusinessUnit
end
go
CREATE TRIGGER trgAfterDelete ON [Derived_Values]
FOR UPDATE
AS
begin
declare @BusinessUnit nvarchar(50)
set @BusinessUnit = 'Deleted Record -- After Delete Trigger.'
insert into
[Derived_Values_Test]
--(BusinessUnit,Questions, Answer)
SELECT
@BusinessUnit + d.BusinessUnit, d.Questions, d.Answer
FROM
deleted d
end
go
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')
UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');
delete Derived_Values;
and then:
SELECT * FROM Derived_Values;
go
select * from Derived_Values_Test;
Record Count: 0;
BUSINESSUNIT QUESTIONS ANSWER
Updated Record -- After Update Trigger.BU1 Q11 Updated Answers A11
Deleted Record -- After Delete Trigger.BU1 Q11 A11
Updated Record -- After Update Trigger.BU1 Q12 Updated Answers A12
Deleted Record -- After Delete Trigger.BU1 Q12 A12
Updated Record -- After Update Trigger.BU2 Q21 Updated Answers A21
Deleted Record -- After Delete Trigger.BU2 Q21 A21
Updated Record -- After Update Trigger.BU2 Q22 Updated Answers A22
Deleted Record -- After Delete Trigger.BU2 Q22 A22
(Update4: If you want to sync: SQLFiddle)
create table Derived_Values
(
BusinessUnit nvarchar(100) not null
,Questions nvarchar(100) not null
,Answer nvarchar(100)
)
go
ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);
create table Derived_Values_Test
(
BusinessUnit nvarchar(150) not null
,Questions nvarchar(100) not null
,Answer nvarchar(100)
)
go
ALTER TABLE Derived_Values_Test ADD CONSTRAINT PK_Derived_Values_Test
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);
CREATE TRIGGER trgAfterInsert ON [Derived_Values]
FOR INSERT
AS
begin
insert
[Derived_Values_Test]
(BusinessUnit,Questions,Answer)
SELECT
i.BusinessUnit, i.Questions, i.Answer
FROM
inserted i
end
go
CREATE TRIGGER trgAfterUpdate ON [Derived_Values]
FOR UPDATE
AS
begin
declare @BusinessUnit nvarchar(50)
set @BusinessUnit = 'Updated Record -- After Update Trigger.'
update
[Derived_Values_Test]
set
--BusinessUnit = i.BusinessUnit
--,Questions = i.Questions
Answer = i.Answer
from
[Derived_Values]
inner join inserted i
on
[Derived_Values].BusinessUnit = i.BusinessUnit
and
[Derived_Values].Questions = i.Questions
end
go
CREATE TRIGGER trgAfterDelete ON [Derived_Values]
FOR DELETE
AS
begin
delete
[Derived_Values_Test]
from
[Derived_Values_Test]
inner join deleted d
on
[Derived_Values_Test].BusinessUnit = d.BusinessUnit
and
[Derived_Values_Test].Questions = d.Questions
end
go
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')
UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');
--delete Derived_Values;
And then:
SELECT * FROM Derived_Values;
go
select * from Derived_Values_Test;
BUSINESSUNIT QUESTIONS ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22
BUSINESSUNIT QUESTIONS ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22
You may find this to be more common on CIFS/SMB network shares. Windows doesn't allow for a file to be written when something else has that file open, and even if the service is not Windows (it might be some other NAS product), it will likely reproduce the same behaviour. Potentially, it might also be a manifestation of some underlying NAS issue vaguely related to locking/replication.
ActiveRecord#where will return an ActiveRecord::Relation object (which will never be nil). Try using .empty? on the relation to test if it will return any records.
Use Viewbag is wrong for sending list to view.You should using Viewmodel in this case. like this:
[HttpGet]
public ActionResult NewAgahi() // New Advertising
{
//--------------------------------------------------------
// ??????? ?? ?????? ???? ????? ??? ??? ?? ???
Country_Repository blCountry = new Country_Repository();
Ostan_Repository blOstan = new Ostan_Repository();
City_Repository blCity = new City_Repository();
Mahale_Repository blMahale = new Mahale_Repository();
Agahi_Repository blAgahi = new Agahi_Repository();
var vm = new NewAgahi_ViewModel();
vm.Country = blCountry.Select();
vm.Ostan = blOstan.Select();
vm.City = blCity.Select();
vm.Mahale = blMahale.Select();
//vm.Agahi = blAgahi.Select();
return View(vm);
}
[ValidateAntiForgeryToken]
[HttpPost]
public ActionResult NewAgahi(Agahi agahi)
{
if (ModelState.IsValid == true)
{
Agahi_Repository blAgahi = new Agahi_Repository();
agahi.Date = DateTime.Now.Date;
agahi.UserId = 1048;
agahi.GroupId = 1;
if (blAgahi.Add(agahi) == true)
{
//Success
return JavaScript("alert('??? ??')");
}
else
{
//Fail
return JavaScript("alert('????? ?? ???')");
}
using ProjectName.Models.DomainModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ProjectName.ViewModels
{
public class NewAgahi_ViewModel // ???? ??????? ???? ?? ??? ??? ?? ?? ???
{
public IEnumerable<Country> Country { get; set; }
public IEnumerable<Ostan> Ostan { get; set; }
public IEnumerable<City> City { get; set; }
public IQueryable<Mahale> Mahale { get; set; }
public ProjectName.Models.DomainModels.Agahi Agahi { get; set; }
}
}
@model ProjectName.ViewModels.NewAgahi_ViewModel
..... .....
@Html.DropDownList("CountryList", new SelectList(Model.Country, "id", "Name"))
@Html.DropDownList("CityList", new SelectList(Model.City, "id", "Name"))
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ProjectName.Models.DomainModels;
namespace ProjectName.Models.Repositories
{
public class Country_Repository : IDisposable
{
private MyWebSiteDBEntities db = null;
public Country_Repository()
{
db = new DomainModels.MyWebSiteDBEntities();
}
public Boolean Add(Country entity, bool autoSave = true)
{
try
{
db.Country.Add(entity);
if (autoSave)
return Convert.ToBoolean(db.SaveChanges());
//return "True";
else
return false;
}
catch (Exception e)
{
string ss = e.Message;
//return e.Message;
return false;
}
}
public bool Update(Country entity, bool autoSave = true)
{
try
{
db.Country.Attach(entity);
db.Entry(entity).State = System.Data.Entity.EntityState.Modified;
if (autoSave)
return Convert.ToBoolean(db.SaveChanges());
else
return false;
}
catch (Exception e)
{
string ss = e.Message; // ?? ?????????? ??? ???? ?????? ?????? ??? ?? ?????
return false;
}
}
public bool Delete(Country entity, bool autoSave = true)
{
try
{
db.Entry(entity).State = System.Data.Entity.EntityState.Deleted;
if (autoSave)
return Convert.ToBoolean(db.SaveChanges());
else
return false;
}
catch
{
return false;
}
}
public bool Delete(int id, bool autoSave = true)
{
try
{
var entity = db.Country.Find(id);
db.Entry(entity).State = System.Data.Entity.EntityState.Deleted;
if (autoSave)
return Convert.ToBoolean(db.SaveChanges());
else
return false;
}
catch
{
return false;
}
}
public Country Find(int id)
{
try
{
return db.Country.Find(id);
}
catch
{
return null;
}
}
public IQueryable<Country> Where(System.Linq.Expressions.Expression<Func<Country, bool>> predicate)
{
try
{
return db.Country.Where(predicate);
}
catch
{
return null;
}
}
public IQueryable<Country> Select()
{
try
{
return db.Country.AsQueryable();
}
catch
{
return null;
}
}
public IQueryable<TResult> Select<TResult>(System.Linq.Expressions.Expression<Func<Country, TResult>> selector)
{
try
{
return db.Country.Select(selector);
}
catch
{
return null;
}
}
public int GetLastIdentity()
{
try
{
if (db.Country.Any())
return db.Country.OrderByDescending(p => p.id).First().id;
else
return 0;
}
catch
{
return -1;
}
}
public int Save()
{
try
{
return db.SaveChanges();
}
catch
{
return -1;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (this.db != null)
{
this.db.Dispose();
this.db = null;
}
}
}
~Country_Repository()
{
Dispose(false);
}
}
}
This is how I did it. This makes the images in the slideshow take up the full screen if it´s aspect ratio allows it, othervice it scales down.
.carousel {
height: 100vh;
width: 100%;
overflow:hidden;
}
.carousel .carousel-inner {
height:100%;
}
To allways get a full screen slideshow, no matter screen aspect ratio, you can also use object-fit: (doesn´t work in IE or Edge)
.carousel .carousel-inner img {
display:block;
object-fit: cover;
}
You can also use -match against a Regular expression. Ex:
if ($dbUserName -match ".{8}" )
{
Write-Output " Please enter more than 8 characters "
$dbUserName=read-host " Re-enter database user name"
}
Also if you're like me and like your curly braces to be in the same horizontal position for your code blocks, you can put that on a new line, since it's expecting a code block it will look on next line. In some commands where the first curly brace has to be in-line with your command, you can use a grave accent marker (`) to tell powershell to treat the next line as a continuation.
If you're array structure will always be multi-dimensional in that exact fashion, then we can iterate through the elements like such:
$fh = fopen('somefile.csv', 'w') or die('Cannot open the file');
for( $i=0; $i<count($arr); $i++ ){
$str = implode( ',', $arr[$i] );
fwrite( $fh, $str );
fwrite( $fh, "\n" );
}
fclose($fh);
That's one way to do it ... you could do it manually but this way is quicker and easier to understand and read.
Then you would manage your headers something what complex857 is doing to spit out the file. You could then delete the file using unlink() if you no longer needed it, or you could leave it on the server if you wished.
You should use partial views. I use the following approach:
Use a view model so you're not passing your domain models to your views:
public class EditPersonViewModel
{
public int Id { get; set; } // this is only used to retrieve record from Db
public string Name { get; set; }
public string Age { get; set; }
}
In your PersonController:
[HttpGet] // this action result returns the partial containing the modal
public ActionResult EditPerson(int id)
{
var viewModel = new EditPersonViewModel();
viewModel.Id = id;
return PartialView("_EditPersonPartial", viewModel);
}
[HttpPost] // this action takes the viewModel from the modal
public ActionResult EditPerson(EditPersonViewModel viewModel)
{
if (ModelState.IsValid)
{
var toUpdate = personRepo.Find(viewModel.Id);
toUpdate.Name = viewModel.Name;
toUpdate.Age = viewModel.Age;
personRepo.InsertOrUpdate(toUpdate);
personRepo.Save();
return View("Index");
}
}
Next create a partial view called _EditPersonPartial
. This contains the modal header, body and footer. It also contains the Ajax form. It's strongly typed and takes in our view model.
@model Namespace.ViewModels.EditPersonViewModel
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Edit group member</h3>
</div>
<div>
@using (Ajax.BeginForm("EditPerson", "Person", FormMethod.Post,
new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
UpdateTargetId = "list-of-people"
}))
{
@Html.ValidationSummary()
@Html.AntiForgeryToken()
<div class="modal-body">
@Html.Bootstrap().ControlGroup().TextBoxFor(x => x.Name)
@Html.Bootstrap().ControlGroup().TextBoxFor(x => x.Age)
</div>
<div class="modal-footer">
<button class="btn btn-inverse" type="submit">Save</button>
</div>
}
Now somewhere in your application, say another partial _peoplePartial.cshtml etc:
<div>
@foreach(var person in Model.People)
{
<button class="btn btn-primary edit-person" data-id="@person.PersonId">Edit</button>
}
</div>
// this is the modal definition
<div class="modal hide fade in" id="edit-person">
<div id="edit-person-container"></div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$('.edit-person').click(function () {
var url = "/Person/EditPerson"; // the url to the controller
var id = $(this).attr('data-id'); // the id that's given to each button in the list
$.get(url + '/' + id, function (data) {
$('#edit-person-container').html(data);
$('#edit-person').modal('show');
});
});
});
</script>
I guess problem is in width attributes in table and td remove 'px' for example
<table border="0" cellpadding="0" cellspacing="0" width="580px" style="background-color: #0290ba;">
Should be
<table border="0" cellpadding="0" cellspacing="0" width="580" style="background-color: #0290ba;">
Or just use Apache CXF's wsdl2java to generate objects you can use.
It is included in the binary package you can download from their website. You can simply run a command like this:
$ ./wsdl2java -p com.mynamespace.for.the.api.objects -autoNameResolution http://www.someurl.com/DefaultWebService?wsdl
It uses the wsdl to generate objects, which you can use like this (object names are also grabbed from the wsdl, so yours will be different a little):
DefaultWebService defaultWebService = new DefaultWebService();
String res = defaultWebService.getDefaultWebServiceHttpSoap11Endpoint().login("webservice","dadsadasdasd");
System.out.println(res);
There is even a Maven plug-in which generates the sources: https://cxf.apache.org/docs/maven-cxf-codegen-plugin-wsdl-to-java.html
Note: If you generate sources using CXF and IDEA, you might want to look at this: https://stackoverflow.com/a/46812593/840315
No, @Controller
is not the same as @Service
, although they both are specializations of @Component
, making them both candidates for discovery by classpath scanning. The @Service
annotation is used in your service layer, and @Controller
is for Spring MVC controllers in your presentation layer. A @Controller
typically would have a URL mapping and be triggered by a web request.
One solution could be to wrap the options inside optgroup:
optgroup { font-size:40px; }
_x000D_
<select>
<optgroup>
<option selected="selected" class="service-small">Service area?</option>
<option class="service-small">Volunteering</option>
<option class="service-small">Partnership & Support</option>
<option class="service-small">Business Services</option>
</optgroup>
</select>
_x000D_
I don't think that one is better than the other in general; it depends on how you intend to use it.
’
).In general I would lean more towards using the character because as you point out it is easier to read and type.
Edit: please see my other answer, as you probably don't need this now.
As you said, in API levels 11+ a HTML5VideoFullScreen$VideoSurfaceView is passed. But I don't think you are right when you say that "it doens't have a MediaPlayer".
This is the way to reach the MediaPlayer instance from the HTML5VideoFullScreen$VideoSurfaceView instance using reflection:
@SuppressWarnings("rawtypes")
Class c1 = Class.forName("android.webkit.HTML5VideoFullScreen$VideoSurfaceView");
Field f1 = c1.getDeclaredField("this$0");
f1.setAccessible(true);
@SuppressWarnings("rawtypes")
Class c2 = f1.getType().getSuperclass();
Field f2 = c2.getDeclaredField("mPlayer");
f2.setAccessible(true);
Object ___html5VideoViewInstance = f1.get(focusedChild); // Look at the code in my other answer to this same question to see whats focusedChild
Object ___mpInstance = f2.get(___html5VideoViewInstance); // This is the MediaPlayer instance.
So, now you could set the onCompletion listener of the MediaPlayer instance like this:
OnCompletionListener ocl = new OnCompletionListener()
{
@Override
public void onCompletion(MediaPlayer mp)
{
// Do stuff
}
};
Method m1 = f2.getType().getMethod("setOnCompletionListener", new Class[] { Class.forName("android.media.MediaPlayer$OnCompletionListener") });
m1.invoke(___mpInstance, ocl);
The code doesn't fail but I'm not completely sure if that onCompletion listener will really be called or if it could be useful to your situation. But just in case someone would like to try it.
CASE might help you out:
SELECT t.first_name,
t.last_name,
t.employid,
t.status
FROM employeetable t
WHERE t.status = (CASE WHEN status_flag = STATUS_ACTIVE THEN 'A'
WHEN status_flag = STATUS_INACTIVE THEN 'T'
ELSE null END)
AND t.business_unit = (CASE WHEN source_flag = SOURCE_FUNCTION THEN 'production'
WHEN source_flag = SOURCE_USER THEN 'users'
ELSE null END)
AND t.first_name LIKE firstname
AND t.last_name LIKE lastname
AND t.employid LIKE employeeid;
The CASE statement evaluates multiple conditions to produce a single value. So, in the first usage, I check the value of status_flag, returning 'A', 'T' or null depending on what it's value is, and compare that to t.status. I do the same for the business_unit column with a second CASE statement.
I tried the option above of moving the plugins but it didn't work. My solution was to delete the entire .metadata folder. This meant that I lost my defaults and had to import my projects again.
I really like the accepted answer. I believe there is yet another way to approach this as well. Let's say you have a very short list of properties that you wouldn't want to ever include in a View, so when updating the entity, those would be omitted. Let's say that those two fields are Password and SSN.
db.Users.Attach(updatedUser);
var entry = db.Entry(updatedUser);
entry.State = EntityState.Modified;
entry.Property(e => e.Password).IsModified = false;
entry.Property(e => e.SSN).IsModified = false;
db.SaveChanges();
This example allows you to essentially leave your business logic alone after adding a new field to your Users table and to your View.
Thanks to dee for the answer above with the Scrape() subroutine. The code worked perfectly as written, and I was able to then convert the code to work with the specific website I am trying to scrape.
I do not have enough reputation to upvote or to comment, but I do actually have some minor improvements to add to dee's answer:
You will need to add the VBA Reference via "Tools\References" to "Microsoft HTML Object Library in order for the code to compile.
I commented out the Browser.Visible line and added the comment as follows
'if you need to debug the browser page, uncomment this line:
'Browser.Visible = True
And I added a line to close the browser before Set Browser = Nothing:
Browser.Quit
Thanks again dee!
ETA: this works on machines with IE9, but not machines with IE8. Anyone have a fix?
Found the fix myself, so came back here to post it. The ClassName function is available in IE9. For this to work in IE8, you use querySelectorAll, with a dot preceding the class name of the object you are looking for:
'Set repList = doc.getElementsByClassName("reportList") 'only works in IE9, not in IE8
Set repList = doc.querySelectorAll(".reportList") 'this works in IE8+
For page loads and modals, the easiest way is to use the ng-show
directive and use one of the scope data variables. Something like:
ng-show="angular.isUndefined(scope.data.someObject)".
Here, while someObject
is undefined, the spinner will show. Once the service returns with data and someObject
is populated, the spinner will return to its hidden state.
Hope to give some extra input in solving this question (or part of it).
This will work for opening an Excel
file from another. A line of code from Mr. Peter L., for the change, use the following:
Application.Workbooks.Open Filename:="C:\Book1withLinkToBook2.xlsx", UpdateLinks:=3
This is in MSDS
. The effect is that it just updates everything (yes, everything) with no warning. This can also be checked if you record a macro.
In MSDS
, it refers this to MS EXCEL 2010
and 2013
. I'm thinking that MS EXCEL 2016
has this covered as well.
I have MS EXCEL 2013
, and have a situation pretty much the same as this topic. So I have a file (call it A
) with Workbook_Open
event code that always get's stuck on the update links prompt.
I have another file (call it B
) connected to this one, and Pivot Tables force me to open the file A
so that the data model can be loaded. Since I want to open the A
file silently in the background, I just use the line that I wrote above, with a Windows("A.xlsx").visible = false
, and, apart from a bigger loading time, I open the A
file from the B
file with no problems or warnings, and fully updated.
'$on' itself returns function for unregister
var unregister= $rootScope.$on('$stateChangeStart',
function(event, toState, toParams, fromState, fromParams, options) {
alert('state changing');
});
you can call unregister() function to unregister that listener
Try
$query = mysql_query("SELECT * FROM users WHERE name = 'Admin' ")or die(mysql_error());
and check if this throw any error.
Then use while($rows = mysql_fetch_assoc($query)):
And finally display it as
echo $name . "<br/>" . $address . "<br/>" . $email . "<br/>" . $subject . "<br/>" . $comment . "<br/><br/>" . ;
Do not user mysql_*
as its deprecated.
You can create a config class witch static properties
class Config
{
static $dbHost = 'localhost';
static $dbUsername = 'user';
static $dbPassword = 'pass';
}
then you can simple use it:
Config::$dbHost
Sometimes in my projects I use a design pattern SINGLETON to access configuration data. It's very comfortable in use.
Why?
For example you have 2 data source in your project. And you can choose witch of them is enabled.
Somewhere in config file you choose:
$dataSource = 'mysql' // or 'json'
When you change source whole app shoud switch to new data source, work fine and dont need change in code.
Example:
Config:
class Config
{
// ....
static $dataSource = 'mysql';
/ .....
}
Singleton class:
class AppConfig
{
private static $instance;
private $dataSource;
private function __construct()
{
$this->init();
}
private function init()
{
switch (Config::$dataSource)
{
case 'mysql':
$this->dataSource = new StorageMysql();
break;
case 'json':
$this->dataSource = new StorageJson();
break;
default:
$this->dataSource = new StorageMysql();
}
}
public static function getInstance()
{
if (empty(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
public function getDataSource()
{
return $this->dataSource;
}
}
... and somewhere in your code (eg. in some service class):
$container->getItemsLoader(AppConfig::getInstance()->getDataSource()) // getItemsLoader need Object of specific data source class by dependency injection
We can obtain an AppConfig object from any place in the system and always get the same copy (thanks to static). The init () method of the class is called In the constructor, which guarantees only one execution. Init() body checks The value of the config $dataSource, and create new object of specific data source class. Now our script can get object and operate on it, not knowing even which specific implementation actually exists.
use strip_tags
$text = '<p>Test paragraph.</p><!-- Comment --> <a href="#fragment">Other text</a>';
echo strip_tags($text); //output Test paragraph. Other text
<?php echo substr(strip_tags($row_get_Business['business_description']),0,110) . "..."; ?>
If you are using Windows command line to print the data, you should use
chcp 65001
This worked for me!
You can follow the below step to modify the .war file name if you are using maven project.
Open pom.xml file of your maven project and go to the tag <build></build>
,
In that give your desired name between this tag :
<finalName></finalName>
.
ex. : <finalName>krutik</finalName>
After deploying this .war you will be able to access url with:
http://localhost:8080/krutik/
If you want to access the url with slash '/' then you will have to specify then name as below:
e.x. : <finalName>krutik#maheta</finalName>
After deploying this .war you will be able to access url with:
http://localhost:8080/krutik/maheta
Your additional threads must be initiated from the same app that is called by the WSGI server.
The example below creates a background thread that executes every 5 seconds and manipulates data structures that are also available to Flask routed functions.
import threading
import atexit
from flask import Flask
POOL_TIME = 5 #Seconds
# variables that are accessible from anywhere
commonDataStruct = {}
# lock to control access to variable
dataLock = threading.Lock()
# thread handler
yourThread = threading.Thread()
def create_app():
app = Flask(__name__)
def interrupt():
global yourThread
yourThread.cancel()
def doStuff():
global commonDataStruct
global yourThread
with dataLock:
# Do your stuff with commonDataStruct Here
# Set the next thread to happen
yourThread = threading.Timer(POOL_TIME, doStuff, ())
yourThread.start()
def doStuffStart():
# Do initialisation stuff here
global yourThread
# Create your thread
yourThread = threading.Timer(POOL_TIME, doStuff, ())
yourThread.start()
# Initiate
doStuffStart()
# When you kill Flask (SIGTERM), clear the trigger for the next thread
atexit.register(interrupt)
return app
app = create_app()
Call it from Gunicorn with something like this:
gunicorn -b 0.0.0.0:5000 --log-config log.conf --pid=app.pid myfile:app
One more variation
Many of the operations done in pandas can also be done as a db query (sql, mongo)
Using a RDBMS or mongodb allows you to perform some of the aggregations in the DB Query (which is optimized for large data, and uses cache and indexes efficiently)
Later, you can perform post processing using pandas.
The advantage of this method is that you gain the DB optimizations for working with large data, while still defining the logic in a high level declarative syntax - and not having to deal with the details of deciding what to do in memory and what to do out of core.
And although the query language and pandas are different, it's usually not complicated to translate part of the logic from one to another.
The below code is tested by myself and is very simple, understandable, usable and fast. This code, initially takes all sheet names, then puts all tables of that excel file in a DataSet.
public static DataSet ToDataSet(string exceladdress, int startRecord = 0, int maxRecord = -1, string condition = "")
{
DataSet result = new DataSet();
using (OleDbConnection connection = new OleDbConnection(
(exceladdress.TrimEnd().ToLower().EndsWith("x"))
? "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + exceladdress + "';" + "Extended Properties='Excel 12.0 Xml;HDR=YES;'"
: "provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + exceladdress + "';Extended Properties=Excel 8.0;"))
try
{
connection.Open();
DataTable schema = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
foreach (DataRow drSheet in schema.Rows)
if (drSheet["TABLE_NAME"].ToString().Contains("$"))
{
string s = drSheet["TABLE_NAME"].ToString();
if (s.StartsWith("'")) s = s.Substring(1, s.Length - 2);
System.Data.OleDb.OleDbDataAdapter command =
new System.Data.OleDb.OleDbDataAdapter(string.Join("", "SELECT * FROM [", s, "] ", condition), connection);
DataTable dt = new DataTable();
if (maxRecord > -1 && startRecord > -1) command.Fill(startRecord, maxRecord, dt);
else command.Fill(dt);
result.Tables.Add(dt);
}
return result;
}
catch (Exception ex) { return null; }
finally { connection.Close(); }
}
Enjoy...
If double quotes does not work , try including the string within square brackets.
For eg:
SELECT "Business Name","Other Name" FROM your_Table
can be changed as
SELECT [Business Name],[Other Name] FROM your_Table
Well you can have each form go to to a different page. (which is preferable)
Or have a different value for the a certain input and base posts on that:
switch($_POST['submit']) {
case 'login':
//...
break;
case 'register':
//...
break;
}
Often when you need to show so many points on the map, you'd be better off using the server-side approach, this article explains when to use each:
Geocoding Strategies: https://developers.google.com/maps/articles/geocodestrat
The client-side limit is not exactly "10 requests per second", and since it's not explained in the API docs I wouldn't rely on its behavior.
You can also use dplyr
's distinct()
function! It tends to be more efficient than alternative options, especially if you have loads of observations.
distinct_data <- dplyr::distinct(yourdata)
pyspellchecker
is the one of the best solutions for this problem. pyspellchecker
library is based on Peter Norvig’s blog post.
It uses a Levenshtein Distance algorithm to find permutations within an edit distance of 2 from the original word.
There are two ways to install this library. The official document highly recommends using the pipev package.
pip
pip install pyspellchecker
git clone https://github.com/barrust/pyspellchecker.git
cd pyspellchecker
python setup.py install
the following code is the example provided from the documentation
from spellchecker import SpellChecker
spell = SpellChecker()
# find those words that may be misspelled
misspelled = spell.unknown(['something', 'is', 'hapenning', 'here'])
for word in misspelled:
# Get the one `most likely` answer
print(spell.correction(word))
# Get a list of `likely` options
print(spell.candidates(word))
GET Request with JSON Query Param
package com.rest.jersey.jerseyclient;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
public class JerseyClientGET {
public static void main(String[] args) {
try {
String BASE_URI="http://vaquarkhan.net:8080/khanWeb";
Client client = Client.create();
WebResource webResource = client.resource(BASE_URI);
ClientResponse response = webResource.accept("application/json").get(ClientResponse.class);
/*if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
*/
String output = webResource.path("/msg/sms").queryParam("search","{\"name\":\"vaquar\",\"surname\":\"khan\",\"ext\":\"2020\",\"age\":\"34\""}").get(String.class);
//String output = response.getEntity(String.class);
System.out.println("Output from Server .... \n");
System.out.println(output);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Post Request :
package com.rest.jersey.jerseyclient;
import com.rest.jersey.dto.KhanDTOInput;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;
public class JerseyClientPOST {
public static void main(String[] args) {
try {
KhanDTOInput khanDTOInput = new KhanDTOInput("vaquar", "khan", "20", "E", null, "2222", "8308511500");
ClientConfig clientConfig = new DefaultClientConfig();
clientConfig.getFeatures().put( JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
Client client = Client.create(clientConfig);
// final HTTPBasicAuthFilter authFilter = new HTTPBasicAuthFilter(username, password);
// client.addFilter(authFilter);
// client.addFilter(new LoggingFilter());
//
WebResource webResource = client
.resource("http://vaquarkhan.net:12221/khanWeb/messages/sms/api/v1/userapi");
ClientResponse response = webResource.accept("application/json")
.type("application/json").put(ClientResponse.class, khanDTOInput);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code :" + response.getStatus());
}
String output = response.getEntity(String.class);
System.out.println("Server response .... \n");
System.out.println(output);
} catch (Exception e) {
e.printStackTrace();
}
}
}
You go to your "device manager", find your "network adapters", then should find the virtual wifi adapter, then right click it and enable it. After that, you start your cmd with admin privileges, then try:
netsh wlan start hostednetwork
To my opinion the best option to route to css & js use the following code:
<link rel="stylesheet" type="text/css" href="{{ URL::to('route/to/css') }}">
So if you have css file called main.css inside of css folder in public folder it should be the following:
<link rel="stylesheet" type="text/css" href="{{ URL::to('css/main.css') }}">
Simplifying @ach's previous solution into one file and using functional interfaces.
public class OperationHelper {
public static void doWithRetry(int maxAttempts, Runnable operation, Consumer<Exception> handle) {
for (int count = 0; count < maxAttempts; count++) {
try {
operation.run();
count = maxAttempts; //don't retry
} catch (Exception e) {
handle.accept(e);
}
}
}
}
If you face this error when you start Symfony project with docker (my Symfony version 5.1). Or errors like these:
Uncaught Exception: Failed to write file "/var/www/html/mysite.com.local/var/cache/dev/App_KernelDevDebugContainer.xml"" while reading upstream
Uncaught Warning: file_put_contents(/var/www/html/mysite.com.local/var/cache/dev/App_KernelDevDebugContainerDeprecations.log): failed to open stream: Permission denied" while reading upstream
Fix below helped me.
In Dockerfile for nginx container add line:
RUN usermod -u 1000 www-data
In Dockerfile for php-fpm container add line:
RUN usermod -u 1000 www-data
Then remove everything in directories "/var/cache", "/var/log" and rebuild docker's containers.
In [Package Manager Console]
try the below
Install-Package NuGet.CommandLine
You need slf4j-api library and slf4j-log4j12-1.7.25 jar. Copy this jars in your project-> WEBINF-> lib folder and in tomcat server lib folder to execute successfully.
How does spring know which polymorphic type to use.
As long as there is only a single implementation of the interface and that implementation is annotated with @Component
with Spring's component scan enabled, Spring framework can find out the (interface, implementation) pair. If component scan is not enabled, then you have to define the bean explicitly in your application-config.xml (or equivalent spring configuration file).
Do I need @Qualifier or @Resource?
Once you have more than one implementation, then you need to qualify each of them and during auto-wiring, you would need to use the @Qualifier
annotation to inject the right implementation, along with @Autowired
annotation. If you are using @Resource (J2EE semantics), then you should specify the bean name using the name
attribute of this annotation.
Why do we autowire the interface and not the implemented class?
Firstly, it is always a good practice to code to interfaces in general. Secondly, in case of spring, you can inject any implementation at runtime. A typical use case is to inject mock implementation during testing stage.
interface IA
{
public void someFunction();
}
class B implements IA
{
public void someFunction()
{
//busy code block
}
public void someBfunc()
{
//doing b things
}
}
class C implements IA
{
public void someFunction()
{
//busy code block
}
public void someCfunc()
{
//doing C things
}
}
class MyRunner
{
@Autowire
@Qualifier("b")
IA worker;
....
worker.someFunction();
}
Your bean configuration should look like this:
<bean id="b" class="B" />
<bean id="c" class="C" />
<bean id="runner" class="MyRunner" />
Alternatively, if you enabled component scan on the package where these are present, then you should qualify each class with @Component
as follows:
interface IA
{
public void someFunction();
}
@Component(value="b")
class B implements IA
{
public void someFunction()
{
//busy code block
}
public void someBfunc()
{
//doing b things
}
}
@Component(value="c")
class C implements IA
{
public void someFunction()
{
//busy code block
}
public void someCfunc()
{
//doing C things
}
}
@Component
class MyRunner
{
@Autowire
@Qualifier("b")
IA worker;
....
worker.someFunction();
}
Then worker
in MyRunner
will be injected with an instance of type B
.
var fs = require('fs'),
http = require('http'),
https = require('https');
var Stream = require('stream').Transform;
var downloadImageToUrl = (url, filename, callback) => {
var client = http;
if (url.toString().indexOf("https") === 0){
client = https;
}
client.request(url, function(response) {
var data = new Stream();
response.on('data', function(chunk) {
data.push(chunk);
});
response.on('end', function() {
fs.writeFileSync(filename, data.read());
});
}).end();
};
downloadImageToUrl('https://www.google.com/images/srpr/logo11w.png', 'public/uploads/users/abc.jpg');
$this->load->library('excel');
$file_name = 'Demo';
$arrHeader = array('Name', 'Mobile');
$arrRows = array(0=>array('Name'=>'Jayant','Mobile'=>54545), 1=>array('Name'=>'Jayant1', 'Mobile'=>44454), 2=>array('Name'=>'Jayant2','Mobile'=>111222), 3=>array('Name'=>'Jayant3', 'Mobile'=>99999));
$this->excel->getActiveSheet()->fromArray($arrHeader,'','A1');
$this->excel->getActiveSheet()->fromArray($arrRows);
header('Content-Type: application/vnd.ms-excel'); //mime type
header('Content-Disposition: attachment;filename="'.$file_name.'"'); //tell browser what's the file name
header('Cache-Control: max-age=0'); //no cache
$objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel5');
$objWriter->save('php://output');
Most comprehensive article on the different options with pros and cons:
Source: https://sunscrapers.com/blog/where-to-put-business-logic-django/
You are applying the formatting to the workbook that has the code, not the added workbook. You'll want to get in the habit of fully qualifying sheet and range references. The code below does that and works for me in Excel 2010:
Sub test()
Dim wb As Excel.Workbook
Set wb = Workbooks.Add
With wb.Sheets(1)
.Range("A1") = "Acctdate"
.Range("B1") = "Ledger"
.Range("C1") = "CY"
.Range("D1") = "BusinessUnit"
.Range("E1") = "OperatingUnit"
.Range("F1") = "LOB"
.Range("G1") = "Account"
.Range("H1") = "TreatyCode"
.Range("I1") = "Amount"
.Range("J1") = "TransactionCurrency"
.Range("K1") = "USDEquivalentAmount"
.Range("L1") = "KeyCol"
.Range("A2", "A50000").Value = Me.TextBox3.Value
.Range("A2", "A50000").NumberFormat = "yyyy-mm-dd"
End With
End Sub
html:
<h4 data-toggle-selector="#me">toggle</h4>
<div id="me">content here</div>
js:
$(function () {
$('[data-toggle-selector]').on('click',function () {
$($(this).data('toggle-selector')).toggle(300);
})
})
It depends on how you tested it, and possibly on differences in the TCP stack implementation of the personal computer and the server.
For example, if your sendall
always completes immediately (or very quickly) on the personal computer, the connection may simply never have broken during sending. This is very likely if your browser is running on the same machine (since there is no real network latency).
In general, you just need to handle the case where a client disconnects before you're finished, by handling the exception.
Remember that TCP communications are asynchronous, but this is much more obvious on physically remote connections than on local ones, so conditions like this can be hard to reproduce on a local workstation. Specifically, loopback connections on a single machine are often almost synchronous.
You can go for identifying a list of elements with xPath:
//td[text() = ' Color Digest ']/following-sibling::td[1]
This will give you a list of two elements, than you can use the 2nd element as your intended one. For example:
List<WebElement> elements = driver.findElements(By.xpath("//td[text() = ' Color Digest ']/following-sibling::td[1]"))
Now, you can use the 2nd element as your intended element, which is elements.get(1)
$('.phone').focus(function(e) {
// add mask
$('.phone')
.mask("(99) 99999999?9")
.focusin(function(event)
{
$(this).unmask();
$(this).mask("(99) 99999999?9");
})
.focusout(function(event)
{
var phone, element;
element = $(this);
phone = element.val().replace(/\D/g, '');
element.unmask();
if (phone.length > 10) {
element.mask("(99) 99999-999?9");
} else {
element.mask("(99) 9999-9999?9");
}
}
);
});
Here is the code you can write color texts
<h3 style="color:#ff0000">Danger</h3>
the position:fixed; property should do the work, I used it on my Website and it worked fine. http://www.w3schools.com/css/css_positioning.asp
I had this issue was trying to remove a ui element inside an event reactive:
myReactives <- eventReactive(input$execute, {
... # Some other long running function here
removeUI(selector = "#placeholder2")
})
I was getting this error, but not on the removeUI element line, it was in the next observer after for some reason. Taking the removeUI method out of the eventReactive and placing it somewhere else removed this error for me.
I had problem too. I switced Port but couldn't start on 8012.
Skype was involved becouse it had the same port - 80. And it couldn't let apache change it's port.
So just restart computer and Before turning on any other programs Open xampp first change port let's say from 80 to 8000 or 8012 on these lines in httpd.conf
Listen 80
ServerName localhost:80
Restart xampp, Start apache, check localhost.
There are some more differences between merge
and persist
(I will enumerate again those already posted here):
D1. merge
does not make the passed entity managed, but rather returns another instance that is managed. persist
on the other side will make the passed entity managed:
//MERGE: passedEntity remains unmanaged, but newEntity will be managed
Entity newEntity = em.merge(passedEntity);
//PERSIST: passedEntity will be managed after this
em.persist(passedEntity);
D2. If you remove an entity and then decide to persist the entity back, you may do that only with persist(), because merge
will throw an IllegalArgumentException
.
D3. If you decided to take care manually of your IDs (e.g by using UUIDs), then a merge
operation will trigger subsequent SELECT
queries in order to look for existent entities with that ID, while persist
may not need those queries.
D4. There are cases when you simply do not trust the code that calls your code, and in order to make sure that no data is updated, but rather is inserted, you must use persist
.
Testing this Javascript:
var arr = [1234563995.721, 12345691212.718, 1234568421.5891, 12345677093.49284];
var sum = 0;
for( var i = 0; i < arr.length; i++ ) {
sum += arr[i];
}
alert( "fMath(sum) = " + Math.round( sum * 1e12 ) / 1e12 );
alert( "fFixed(sum) = " + sum.toFixed( 5 ) );
Dont use Math.round( (## + ## + ... + ##) * 1e12) / 1e12
Instead, use ( ## + ## + ... + ##).toFixed(5) )
In IE 9, toFixed
works very well.
You are looking for map_keys, with it you can write things like
BOOST_FOREACH(const key_t key, the_map | boost::adaptors::map_keys)
{
// do something with key
}
For the exact result, I'd rather calculate it, but using display format.
Assuming A1 cell has value 29773945664927.
Count the number of commas in B1 cell.
=QUOTIENT(LEN(A1)-1,3)
Divide the value by 1024^B1 in C1 cell.
=A1/1024^B1
Display unit in D1 cell.
=SWITCH(B1, 5," PB", 4," TB", 3," GB", 2," MB",1," KB",0," B")
Hide B1 cell.
If you've tried modifying etc/hosts and adding java.rmi.server.hostname property as well but still registry is being bind to 127.0.0.1
the issue for me was resolved after explicitly setting System property through code though the same property wasn't picked from jvm args
The error message:
merge: remote/master - not something we can merge
is saying that Git doesn't recognize remote/master
. This is probably because you don't have a "remote" named "remote". You have a "remote" named "origin".
Think of "remotes" as an alias for the url to your Git server. master
is your locally checked-out version of the branch. origin/master
is the latest version of master
from your Git server that you have fetched (downloaded). A fetch
is always safe because it will only update the "origin/x" version of your branches.
So, to get your master
branch back in sync, first download the latest content from the git server:
git fetch
Then, perform the merge:
git merge origin/master
...But, perhaps the better approach would be:
git pull origin master
The pull
command will do the fetch
and merge
for you in one step.
Combining the previous answers provides these solutions:
if (typeof str == 'string' || str instanceof String)
or
Object.prototype.toString.call(str) == '[object String]'
objectForKey:
is an NSDictionary
method. An NSDictionary
is a collection class similar to an NSArray
, except instead of using indexes, it uses keys to differentiate between items. A key is an arbitrary string you provide. No two objects can have the same key (just as no two objects in an NSArray
can have the same index).
valueForKey:
is a KVC method. It works with ANY class. valueForKey:
allows you to access a property using a string for its name. So for instance, if I have an Account
class with a property accountNumber
, I can do the following:
NSNumber *anAccountNumber = [NSNumber numberWithInt:12345];
Account *newAccount = [[Account alloc] init];
[newAccount setAccountNumber:anAccountNUmber];
NSNumber *anotherAccountNumber = [newAccount accountNumber];
Using KVC, I can access the property dynamically:
NSNumber *anAccountNumber = [NSNumber numberWithInt:12345];
Account *newAccount = [[Account alloc] init];
[newAccount setValue:anAccountNumber forKey:@"accountNumber"];
NSNumber *anotherAccountNumber = [newAccount valueForKey:@"accountNumber"];
Those are equivalent sets of statements.
I know you're thinking: wow, but sarcastically. KVC doesn't look all that useful. In fact, it looks "wordy". But when you want to change things at runtime, you can do lots of cool things that are much more difficult in other languages (but this is beyond the scope of your question).
If you want to learn more about KVC, there are many tutorials if you Google especially at Scott Stevenson's blog. You can also check out the NSKeyValueCoding Protocol Reference.
Hope that helps.
The standard best practice for REST APIs is to have a hyphen, not camelcase or underscores.
This comes from Mark Masse's "REST API Design Rulebook" from Oreilly.
In addition, note that Stack Overflow itself uses hyphens in the URL: .../hyphen-underscore-or-camelcase-as-word-delimiter-in-uris
As does WordPress: http://inventwithpython.com/blog/2012/03/18/how-much-math-do-i-need-to-know-to-program-not-that-much-actually
For anyone looking into this question recently especially if testing using npm
or yarn
directly
Currently, you don't have to change the configuration options
As per Jest official website, you can do the following to generate coverage reports:
You must put --
before passing the --coverage
argument of Jest
npm test -- --coverage
if you try invoking the --coverage
directly without the --
it won't work
You can pass the --coverage
argument of jest directly
yarn test --coverage
Returning the whole object on an update would not seem very relevant, but I can hardly see why returning the whole object when it is created would be a bad practice in a normal use case. This would be useful at least to get the ID easily and to get the timestamps when relevant. This is actually the default behavior got when scaffolding with Rails.
I really do not see any advantage to returning only the ID and doing a GET request after, to get the data you could have got with your initial POST.
Anyway as long as your API is consistent I think that you should choose the pattern that fits your needs the best. There is not any correct way of how to build a REST API, imo.
function calcualteMonthYr(){
var fromDate =new Date($('#txtDurationFrom2').val()); //date picker (text fields)
var toDate = new Date($('#txtDurationTo2').val());
var months=0;
months = (toDate.getFullYear() - fromDate.getFullYear()) * 12;
months -= fromDate.getMonth();
months += toDate.getMonth();
if (toDate.getDate() < fromDate.getDate()){
months--;
}
$('#txtTimePeriod2').val(months);
}
You can use VLOOKUP
.
Assuming those are in columns A and B in Sheet1 and Sheet2 each, 22350 is in cell A2 of Sheet1, you can use:
=VLOOKUP(A2, Sheet2!A:B, 2, 0)
This will return you #N/A
if there are no matches. Drag/Fill/Copy&Paste the formula to the bottom of your table and that should do it.
If your app use multiple webview you will still have troubles : localStorage is not correctly shared accross all webviews.
If you want to share the same data in multiple webviews the only way is to repair it with a java database and a javascript interface.
This page on github shows how to do this.
hope this help!
You can update the configuration with a little hack, under your root directory:
replace --your directory of choice-- with the folder directory you want it to build on
note the path I provided can be a bit dirty, but this is all you need to do to modify the configuration.
import sys
sys.stdout.write('h')
sys.stdout.flush()
sys.stdout.write('m')
sys.stdout.flush()
You need to call sys.stdout.flush()
because otherwise it will hold the text in a buffer and you won't see it.
$data = json_decode(...);
$firstId = $data[0]["id"];
$secondSeatNo = $data[1]["seat_no"];
Just like this :)
If you have done this to make sure the user can't close the window:
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
Then you should change your pullThePlug()
method to be
public void pullThePlug() {
// this will make sure WindowListener.windowClosing() et al. will be called.
WindowEvent wev = new WindowEvent(this, WindowEvent.WINDOW_CLOSING);
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(wev);
// this will hide and dispose the frame, so that the application quits by
// itself if there is nothing else around.
setVisible(false);
dispose();
// if you have other similar frames around, you should dispose them, too.
// finally, call this to really exit.
// i/o libraries such as WiiRemoteJ need this.
// also, this is what swing does for JFrame.EXIT_ON_CLOSE
System.exit(0);
}
I found this to be the only way that plays nice with the WindowListener
and JFrame.DO_NOTHING_ON_CLOSE
.
There are two issues here. The first is to access fields in the array returned by your JSON parse, the second is to rename collections/fields (like sentences) away from VBA reserved names.
Let's address the second concern first. You were on the right track. First, replace all instances of sentences
with jsentences
If text within your JSON also contains the word sentences, then figure out a way to make the replacement unique, such as using "sentences":[
as the search string. You can use the VBA Replace
method to do this.
Once that's done, so VBA will stop renaming sentences to Sentences, it's just a matter of accessing the array like so:
'first, declare the variables you need:
Dim jsent as Variant
'Get arr all setup, then
For Each jsent in arr.jsentences
MsgBox(jsent.orig)
Next
You do not include a <scope>
tag in your dependency. If you add it, your dependency becomes something like:
<dependency>
<groupId>org.openrdf.sesame</groupId>
<artifactId>sesame-runtime</artifactId>
<version>2.7.2</version>
<scope> ... </scope>
</dependency>
The "scope" tag tells maven at which stage of the build your dependency is needed. Examples for the values to put inside are "test", "provided" or "runtime" (omit the quotes in your pom). I do not know your dependency so I cannot tell you what value to choose. Please consult the Maven documentation and the documentation of your dependency.
Ubuntu these days comes with ufw - Uncomplicated Firewall. ufw is an easy-to-use method of handling iptables rules.
Try using this command to allow a port
sudo ufw allow 1701
To test connectivity, you could try shutting down the VPN software (freeing up the ports) and using netcat to listen, like this:
nc -l 1701
Then use telnet from your Windows host and see what shows up on your Ubuntu terminal. This can be repeated for each port you'd like to test.
URL safe Base64 Encoding/Decoding
public static class Base64Url
{
public static string Encode(string text)
{
return Convert.ToBase64String(Encoding.UTF8.GetBytes(text)).TrimEnd('=').Replace('+', '-')
.Replace('/', '_');
}
public static string Decode(string text)
{
text = text.Replace('_', '/').Replace('-', '+');
switch (text.Length % 4)
{
case 2:
text += "==";
break;
case 3:
text += "=";
break;
}
return Encoding.UTF8.GetString(Convert.FromBase64String(text));
}
}
@FurkanO has provided the right approach. Though to go for a more cleaner approach (es6 way) you can do something like this
[{
name: 'Sam',
email: '[email protected]'
},
{
name: 'Ash',
email: '[email protected]'
}
].map( ( {name, email} ) => {
return <p key={email}>{name} - {email}</p>
})
Cheers!
For a sample app.config file like below:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="countoffiles" value="7" />
<add key="logfilelocation" value="abc.txt" />
</appSettings>
</configuration>
You read the above application settings using the code shown below:
using System.Configuration;
You may also need to also add a reference to System.Configuration
in your project if there isn't one already. You can then access the values like so:
string configvalue1 = ConfigurationManager.AppSettings["countoffiles"];
string configvalue2 = ConfigurationManager.AppSettings["logfilelocation"];
The bottom line is not all browsers will actually look for your favicon.ico file. Some browsers allow users to choose whether or not it should automatically look. Therefore, in order to ensure that it will always appear and get looked at, you do have to define it.
If your HTML page looks like this:
<input type="checkbox" name="test" value="value1">
After submitting the form you can check it with:
isset($_POST['test'])
or
if ($_POST['test'] == 'value1') ...
In the (not too) early days, all that existed was ASCII. This was okay, as all that would ever be needed were a few control characters, punctuation, numbers and letters like the ones in this sentence. Unfortunately, today's strange world of global intercommunication and social media was not foreseen, and it is not too unusual to see English, ???????, ??, ????????, e???????, and ????????? in the same document (I hope I didn't break any old browsers).
But for argument's sake, lets say Joe Average is a software developer. He insists that he will only ever need English, and as such only wants to use ASCII. This might be fine for Joe the user, but this is not fine for Joe the software developer. Approximately half the world uses non-Latin characters and using ASCII is arguably inconsiderate to these people, and on top of that, he is closing off his software to a large and growing economy.
Therefore, an encompassing character set including all languages is needed. Thus came Unicode. It assigns every character a unique number called a code point. One advantage of Unicode over other possible sets is that the first 256 code points are identical to ISO-8859-1, and hence also ASCII. In addition, the vast majority of commonly used characters are representable by only two bytes, in a region called the Basic Multilingual Plane (BMP). Now a character encoding is needed to access this character set, and as the question asks, I will concentrate on UTF-8 and UTF-16.
So how many bytes give access to what characters in these encodings?
It's worth mentioning now that characters not in the BMP include ancient scripts, mathematical symbols, musical symbols, and rarer Chinese/Japanese/Korean (CJK) characters.
If you'll be working mostly with ASCII characters, then UTF-8 is certainly more memory efficient. However, if you're working mostly with non-European scripts, using UTF-8 could be up to 1.5 times less memory efficient than UTF-16. When dealing with large amounts of text, such as large web-pages or lengthy word documents, this could impact performance.
Note: If you know how UTF-8 and UTF-16 are encoded, skip to the next section for practical applications.
1
to avoid clashing with the ASCII characters.As can be seen, UTF-8 and UTF-16 are nowhere near compatible with each other. So if you're doing I/O, make sure you know which encoding you are using! For further details on these encodings, please see the UTF FAQ.
Character and String data types: How are they encoded in the programming language? If they are raw bytes, the minute you try to output non-ASCII characters, you may run into a few problems. Also, even if the character type is based on a UTF, that doesn't mean the strings are proper UTF. They may allow byte sequences that are illegal. Generally, you'll have to use a library that supports UTF, such as ICU for C, C++ and Java. In any case, if you want to input/output something other than the default encoding, you will have to convert it first.
Recommended/default/dominant encodings: When given a choice of which UTF to use, it is usually best to follow recommended standards for the environment you are working in. For example, UTF-8 is dominant on the web, and since HTML5, it has been the recommended encoding. Conversely, both .NET and Java environments are founded on a UTF-16 character type. Confusingly (and incorrectly), references are often made to the "Unicode encoding", which usually refers to the dominant UTF encoding in a given environment.
Library support: The libraries you are using support some kind of encoding. Which one? Do they support the corner cases? Since necessity is the mother of invention, UTF-8 libraries will generally support 4-byte characters properly, since 1, 2, and even 3 byte characters can occur frequently. However, not all purported UTF-16 libraries support surrogate pairs properly since they occur very rarely.
Counting characters: There exist combining characters in Unicode. For example the code point U+006E (n), and U+0303 (a combining tilde) forms ñ, but the code point U+00F1 forms ñ. They should look identical, but a simple counting algorithm will return 2 for the first example, 1 for the latter. This isn't necessarily wrong, but may not be the desired outcome either.
Comparing for equality: A, А, and Α look the same, but they're Latin, Cyrillic, and Greek respectively. You also have cases like C and Ⅽ, one is a letter, the other a Roman numeral. In addition, we have the combining characters to consider as well. For more info see Duplicate characters in Unicode.
Surrogate pairs: These come up often enough on SO, so I'll just provide some example links:
Others?:
I noticed two popular approaches for this question: one using array_values()
and other using key()
. To find out which is faster, I wrote a small program:
$arrays = Array(
'Array #1' => Array(1, 2, 3, 54, 23, 212, 123, 1, 1),
'Array #2' => Array("Stack", 1.5, 20, Array(3.4)),
'Array #3' => Array(1 => 4, 2 => 2),
'Array #4' => Array(3.0, "2", 3000, "Stack", 5 => "4"),
'Array #5' => Array("3" => 4, "2" => 2),
'Array #6' => Array("0" => "One", 1.0 => "Two", 2 => "Three"),
'Array #7' => Array(3 => "asdf", 4 => "asdf"),
'Array #8' => Array("apple" => 1, "orange" => 2),
);
function is_indexed_array_1(Array &$arr) {
return $arr === array_values($arr);
}
function is_indexed_array_2(Array &$arr) {
for (reset($arr), $i = 0; key($arr) === $i++; next($arr))
;
return is_null(key($arr));
}
// Method #1
$start = microtime(true);
for ($i = 0; $i < 1000; $i++) {
foreach ($arrays as $array) {
$dummy = is_indexed_array_1($array);
}
}
$end = microtime(true);
echo "Time taken with method #1 = ".round(($end-$start)*1000.0,3)."ms\n";
// Method #2
$start = microtime(true);
for ($i = 0; $i < 1000; $i++) {
foreach ($arrays as $array) {
$dummy = is_indexed_array_2($array);
}
}
$end = microtime(true);
echo "Time taken with method #1 = ".round(($end-$start)*1000.0,3)."ms\n";
Output for the program on PHP 5.2 on CentOS is as follows:
Time taken with method #1 = 10.745ms
Time taken with method #2 = 18.239ms
Output on PHP 5.3 yielded similar results. Obviously using array_values()
is much faster.
You can log in via browser and copy the needed headers afterwards:
Use "Copy as cURL" in the Network tab of browser developer tools and replace curl's flag -H
with wget's --header
(and also --data
with --post-data
if needed).
For printing log use this function, this will create log file in log
folder. Create log folder if its not exists .
logger("Your msg in log ", "Filename you want ", "Data to be log string or array or object");
function logger($logMsg="logger", $filename="logger", $logData=""){
$log = date("j.n.Y h:i:s")." || $logMsg : ".print_r($logData,1).PHP_EOL .
"-------------------------".PHP_EOL;
file_put_contents('./log/'.$filename.date("j.n.Y").'.log', $log, FILE_APPEND);
}
Assuming your page is available under "http://example.com"
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()
driver.get("http://example.com")
Select element by id:
inputElement = driver.find_element_by_id("a1")
inputElement.send_keys('1')
Now you can simulate hitting ENTER:
inputElement.send_keys(Keys.ENTER)
or if it is a form you can submit:
inputElement.submit()
If slicing could work on iterators...
from itertools import islice
with open(fname) as f:
for line in islice(f, 1, None):
pass
The original variables you listed can be declared and assigned to the same value in a short line of code using destructuring assignment. The keywords let
, const
, and var
can all be used for this type of assignment.
let [moveUp, moveDown, moveLeft, moveRight, mouseDown, touchDown] = Array(6).fill(false);
Rotate the x axis labels with angle equal or smaller than 90 degrees using base graphics. Code adapted from the R FAQ:
par(mar = c(7, 4, 2, 2) + 0.2) #add room for the rotated labels
#use mtcars dataset to produce a barplot with qsec colum information
mtcars = mtcars[with(mtcars, order(-qsec)), ] #order mtcars data set by column "qsec"
end_point = 0.5 + nrow(mtcars) + nrow(mtcars) - 1 #this is the line which does the trick (together with barplot "space = 1" parameter)
barplot(mtcars$qsec, col = "grey50",
main = "",
ylab = "mtcars - qsec", ylim = c(0,5 + max(mtcars$qsec)),
xlab = "",
space = 1)
#rotate 60 degrees (srt = 60)
text(seq(1.5, end_point, by = 2), par("usr")[3]-0.25,
srt = 60, adj = 1, xpd = TRUE,
labels = paste(rownames(mtcars)), cex = 0.65)
docker image prune removes all dangling images (those with tag none). docker image prune -a would also remove any images that have no container that uses them.
The difference between dangling and unused images is explained in this stackoverflow thread.
You can also use .filter()
$('.slide-link').filter('[data-slide="0"]').addClass('active');
I added the start
and exit
which works. Without both it was not working
start C:/Anaconda3/Library/bin/pyrcc4.exe -py3 {path}/Resourses.qrc -{path}/Resourses_rc.py
exit
On newer versions of OS X you should find ALL JREs (and JDKs) under
/Library/Java/JavaVirtualMachines/
/System/Library/Java/JavaVirtualMachines/
the old path
/System/Library/Frameworks/JavaVM.framework/
has been deprecated.
Here is the official deprecation note:
NuGet (formerly NuPack) is a free, open source developer focused package management system for the .NET platform intent on simplifying the process of incorporating third party libraries into a .NET application during development.
What you want to do is put the console into "raw" mode (line editing bypassed and no enter key required) as opposed to "cooked" mode (line editing with enter key required.) On UNIX systems, the 'stty' command can change modes.
Now, with respect to Java... see Non blocking console input in Python and Java. Excerpt:
If your program must be console based, you have to switch your terminal out of line mode into character mode, and remember to restore it before your program quits. There is no portable way to do this across operating systems.
One of the suggestions is to use JNI. Again, that's not very portable. Another suggestion at the end of the thread, and in common with the post above, is to look at using jCurses.
Try closing any programs that have the folder open, such as editors, explorer windows, command prompts, and FTP programs. This always fixes the issue for me on Windows.
If my understanding is correct then you want to match any line which has Clinton and Reagan, in any order, but not Bush. As suggested by Stuck, here is a version with lookahead assertions:
#!/usr/bin/perl
use strict;
use warnings;
my $regex = qr/
(?=.*clinton)
(?!.*bush)
.*reagan
/ix;
while (<DATA>) {
chomp;
next unless (/$regex/);
print $_, "\n";
}
__DATA__
shouldn't match - reagan came first, then clinton, finally bush
first match - first two: reagan and clinton
second match - first two reverse: clinton and reagan
shouldn't match - last two: clinton and bush
shouldn't match - reverse: bush and clinton
shouldn't match - and then came obama, along comes mary
shouldn't match - to clinton with perl
Results
first match - first two: reagan and clinton
second match - first two reverse: clinton and reagan
as desired it matches any line which has Reagan and Clinton in any order.
You may want to try reading how lookahead assertions work with examples at http://www252.pair.com/comdog/mastering_perl/Chapters/02.advanced_regular_expressions.html
they are very tasty :)
It's not clear how you want your Date logic to behave? Usually a good way to deal with default behaviour is the Null Object pattern.
First Off, I object to this other question regarding Visual Studio 2015 as a duplicate question. How do I open SSRS (.rptproj) and SSIS (.dtproj) files in Visual Studio 2015? [duplicate]
Basically this question has the title ...Visual Studio 2012 / 2013
What about ALL the improvements and changes to VS 2015 ??? SSDT has been updated and changed. The entire way of doing various additions and updates is different.
So having vented / rant - I did open a VS 2015 update 2 instance and proceeded to open an existing solution that include a .rptproj
project. Now this computer does not yet have sql server installed on it yet.
Solution for ME : Tools --> Extension and Updates --> Updates --> sql server tooling updates
Click on Update button and wait a long time and SSDT then installs and close visual studio 2015 and re-open and it works for me.
In case it is NOT found in VS 2015 for some reason : scroll to the bottom, pick your language iso https://msdn.microsoft.com/en-us/mt186501.aspx?f=255&MSPPError=-2147217396
my.ini
max_allowed_packet = 800M
read_buffer_size = 2014K
PHP.ini
max_input_time = 20000
memory_limit = 128M
post_max_size=128M
The code you listed kind of looks like a Lehmer RNG. If this is the case, then 2147483647
is the largest 32-bit signed integer, 2147483647
is the largest 32-bit prime, and 48271
is a full-period multiplier that is used to generate the numbers.
If this is true, you could modify RandomNumberGenerator
to take in an extra parameter seed
, and then set this.seed
to seed
; but you'd have to be careful to make sure the seed would result in a good distribution of random numbers (Lehmer can be weird like that) -- but most seeds will be fine.
To retrieve data from form which send post request you can do it like this
def login_view(request):
if(request.POST):
login_data = request.POST.dict()
username = login_data.get("username")
password = login_data.get("password")
user_type = login_data.get("user_type")
print(user_type, username, password)
return HttpResponse("This is a post request")
else:
return render(request, "base.html")
Basically, if your image is
<img id='Img1' src='someurl'>
then you can convert it like
var c = document.createElement('canvas');
var img = document.getElementById('Img1');
c.height = img.naturalHeight;
c.width = img.naturalWidth;
var ctx = c.getContext('2d');
ctx.drawImage(img, 0, 0, c.width, c.height);
var base64String = c.toDataURL();
public class **Your java Class** extends ActionBarActivity implements View.OnClickListener{
date = (EditText) findViewById(R.id.date);
date.setInputType(InputType.TYPE_NULL);
date.requestFocus();
date.setOnClickListener(this);
dateFormatter = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
setDateTimeField();
private void setDateTimeField() {
Calendar newCalendar = Calendar.getInstance();
fromDatePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
date.setText(dateFormatter.format(newDate.getTime()));
}
}, newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
}
@Override
public void onClick(View v) {
fromDatePickerDialog.show();
}
}
Often the reason you want to reverse the vector is because you fill it by pushing all the items on at the end but were actually receiving them in reverse order. In that case you can reverse the container as you go by using a deque
instead and pushing them directly on the front. (Or you could insert the items at the front with vector::insert()
instead, but that would be slow when there are lots of items because it has to shuffle all the other items along for every insertion.) So as opposed to:
std::vector<int> foo;
int nextItem;
while (getNext(nextItem)) {
foo.push_back(nextItem);
}
std::reverse(foo.begin(), foo.end());
You can instead do:
std::deque<int> foo;
int nextItem;
while (getNext(nextItem)) {
foo.push_front(nextItem);
}
// No reverse needed - already in correct order
I got the same error using:
<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Source+Sans+Pro:400,400i,700,700i,900,900i" type="text/css" media="all">
But once I added https: in the beginning of the href the error disappeared.
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,400i,700,700i,900,900i" type="text/css" media="all">
Change
Range(DataImportColumn & DataImportRow).Offset(0, 2).Value
to
Cells(DataImportRow,DataImportColumn).Value
When you just have the row and the column then you can use the cells()
object. The syntax is Cells(Row,Column)
Also one more tip. You might want to fully qualify your Cells
object. for example
ThisWorkbook.Sheets("WhatEver").Cells(DataImportRow,DataImportColumn).Value
I have been struggling with out-of-memory experience using various way to explode my lists so I prepared some benchmarks to help me decide which answers to upvote. I tested five scenarios with varying proportions of the list length to the number of lists. Sharing the results below:
Time: (less is better, click to view large version)
Peak memory usage: (less is better)
Conclusions:
Full details (functions and benchmarking code) are in this GitHub gist. Please note that the benchmark problem was simplified and did not include splitting of strings into the list - which most solutions performed in a similar fashion.
You need a semicolon after font-family: Arial, Helvetica, sans-serif
. This will make your updated code the following:
<!DOCTYPE>
<html>
<head>
<title>DIV Font</title>
<style>
.my_text
{
font-family: Arial, Helvetica, sans-serif;
font-size: 40px;
font-weight: bold;
}
</style>
</head>
<body>
<div class="my_text">some text</div>
</body>
</html>
Here is the answer for those of you looking like I did all over the web trying to find out how to do this task. Uploading a photo to a server with the file name stored in a mysql database and other form data you want in your Database. Please let me know if it helped.
Firstly the form you need:
<form method="post" action="addMember.php" enctype="multipart/form-data">
<p>
Please Enter the Band Members Name.
</p>
<p>
Band Member or Affiliates Name:
</p>
<input type="text" name="nameMember"/>
<p>
Please Enter the Band Members Position. Example:Drums.
</p>
<p>
Band Position:
</p>
<input type="text" name="bandMember"/>
<p>
Please Upload a Photo of the Member in gif or jpeg format. The file name should be named after the Members name. If the same file name is uploaded twice it will be overwritten! Maxium size of File is 35kb.
</p>
<p>
Photo:
</p>
<input type="hidden" name="size" value="350000">
<input type="file" name="photo">
<p>
Please Enter any other information about the band member here.
</p>
<p>
Other Member Information:
</p>
<textarea rows="10" cols="35" name="aboutMember">
</textarea>
<p>
Please Enter any other Bands the Member has been in.
</p>
<p>
Other Bands:
</p>
<input type="text" name="otherBands" size=30 />
<br/>
<br/>
<input TYPE="submit" name="upload" title="Add data to the Database" value="Add Member"/>
</form>
Then this code processes you data from the form:
<?php
// This is the directory where images will be saved
$target = "your directory";
$target = $target . basename( $_FILES['photo']['name']);
// This gets all the other information from the form
$name=$_POST['nameMember'];
$bandMember=$_POST['bandMember'];
$pic=($_FILES['photo']['name']);
$about=$_POST['aboutMember'];
$bands=$_POST['otherBands'];
// Connects to your Database
mysqli_connect("yourhost", "username", "password") or die(mysqli_error()) ;
mysqli_select_db("dbName") or die(mysqli_error()) ;
// Writes the information to the database
mysqli_query("INSERT INTO tableName (nameMember,bandMember,photo,aboutMember,otherBands)
VALUES ('$name', '$bandMember', '$pic', '$about', '$bands')") ;
// Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
// Tells you if its all ok
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory";
}
else {
// Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>
Code edited from www.about.com
I published the vue-unique-id Vue plugin for this on npm.
None of the other solutions address the requirement of having more than one form element in your component. Here's my take on a plugin that builds on previously given answers:
Vue.use((Vue) => {
// Assign a unique id to each component
let uuid = 0;
Vue.mixin({
beforeCreate: function() {
this.uuid = uuid.toString();
uuid += 1;
},
});
// Generate a component-scoped id
Vue.prototype.$id = function(id) {
return "uid-" + this.uuid + "-" + id;
};
});
This doesn't rely on the internal _uid
property which is reserved for internal use.
Use it like this in your component:
<label :for="$id('field1')">Field 1</label>
<input :id="$id('field1')" type="text" />
<label :for="$id('field2')">Field 2</label>
<input :id="$id('field2')" type="text" />
To produce something like this:
<label for="uid-42-field1">Field 1</label>
<input id="uid-42-field1" type="text" />
<label for="uid-42-field2">Field 2</label>
<input id="uid-42-field2" type="text" />
This is an oldie, and there are a few solutions out there, but I came up with a shorter and simpler formula than any other I encountered, and it might be useful to anyone passing by.
I have named the colors list Colors
(A2:A7), and the array formula put in cell C2 is this (fixed):
=IFERROR(INDEX(Colors,MATCH(SUM(COUNTIF(C$1:C1,Colors)),COUNTIF(Colors,"<"&Colors),0)),"")
Use Ctrl+Shift+Enter
to enter the formula in C2, and copy C2 down to C3:C7.
Explanation with sample data {"red"; "blue"; "red"; "green"; "blue"; "black"}:
COUNTIF(Colors,"<"&Colors)
returns an array (#1) with the count of values that are smaller then each item in the data {4;1;4;3;1;0} (black=0 items smaller, blue=1 item, red=4 items). This can be translated to a sort value for each item.COUNTIF(C$1:C...,Colors)
returns an array (#2) with 1 for each data item that is already in the sorted result. In C2 it returns {0;0;0;0;0;0} and in C3 {0;0;0;0;0;1} because "black" is first in the sort and last in the data. In C4 {0;1;0;0;1;1} it indicates "black" and all the occurrences of "blue" are already present.SUM
returns the k-th sort value, by counting all the smaller values occurrences that are already present (sum of array #2).MATCH
finds the first index of the k-th sort value (index in array #1).IFERROR
is only to hide the #N/A
error in the bottom cells, when the sorted unique list is complete.To know how many unique items you have you can use this regular formula:
=SUM(IF(FREQUENCY(COUNTIF(Colors,"<"&Colors),COUNTIF(Colors,"<"&Colors)),1))
It looks like NUnit Framework 2.6.4 does not work well with NUnit Test Adapter. In the website it mentions the test adapter will only work with NUnit Framework 2.6.3.
This was my problem: 1. I had downloaded NUnit and NUnit Test Adapter separately through Nuget in the VS2012. Somehow NUnit got updated to 2.6.4 Suddenly i did not see my test cases listed.
Fix:
Uninstall Nuget and Nuget Test adapter
a. Go to Tools> Nuget > Nuget Pkg manager > Manage Nuget Pkg for Solution
b. List installed packages
c. Click manage
d. Un-check your projects
Install NUnit Test Adapter including NUnit 2.6.3 Framework
Clean/Rebuild solution
Open Test > Test Explorer > Run All
I see all the test cases
Hope this helps
A note for Christoph's answer: Facebook Oauth Logout The logout function requires a callback function to be specified and will fail without it, at least on Firefox. Chrome works without the callback.
FB.logout(function(response) {});
python: read lines from compressed text files
Using gzip.GzipFile
:
import gzip
with gzip.open('input.gz','r') as fin:
for line in fin:
print('got line', line)
.box-author-txt {width:596px; float:left; padding:5px 0px 10px 10px; border:1px #dddddd solid; -moz-border-radius: 0 0 5px 5px; -webkit-border-radius: 0 0 5px 5px; -o-border-radius: 0 0 5px 5px; border-radius: 0 0 5px 5px; overflow-x: scroll; white-space: nowrap; overflow-y: hidden;}
.box-author-txt ul{ vertical-align:top; height:auto; display: inline-block; white-space: nowrap; margin:0 9px 0 0; padding:0px;}
.box-author-txt ul li{ list-style-type:none; width:140px; }
You have to free()
the allocated memory in exact reverse order of how it was allocated using malloc()
.
Note that You should free the memory only after you are done with your usage of the allocated pointers.
memory allocation for 1D arrays:
buffer = malloc(num_items*sizeof(double));
memory deallocation for 1D arrays:
free(buffer);
memory allocation for 2D arrays:
double **cross_norm=(double**)malloc(150 * sizeof(double *));
for(i=0; i<150;i++)
{
cross_norm[i]=(double*)malloc(num_items*sizeof(double));
}
memory deallocation for 2D arrays:
for(i=0; i<150;i++)
{
free(cross_norm[i]);
}
free(cross_norm);
Here's what's been working for me:
<plugin>
<artifactId>exec-maven-plugin</artifactId>
<groupId>org.codehaus.mojo</groupId>
<executions>
<execution><!-- Run our version calculation script -->
<id>Version Calculation</id>
<phase>generate-sources</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>${basedir}/scripts/calculate-version.sh</executable>
</configuration>
</execution>
</executions>
</plugin>
When using implode
and you see:
Psychologist intervened, cancelling implosion, crisis avoided :)
Then you may want to use --force
rvm implode --force
Then remove RVM from the following locations:
rm -rf /usr/local/rvm
sudo rm /etc/profile.d/rvm.sh
sudo rm /etc/rvmrc
sudo rm ~/.rvmrc
Check the following files and remove or comment out references to RVM:
~/.bashrc
~/.bash_profile
~/.profile
~/.zshrc
~/.zlogin
Comment-out/remove the following lines from /etc/profile:
source /etc/profile.d/sm.sh
source /etc/profile.d/rvm.sh
/etc/profile is a read-only file so use:
sudo vim /etc/profile
And after making the change write using a bang!
:w!
Finally re-login/restart your terminal.
This should certainly work:
hive --version
I'd create a cte and do an inner join. It's not efficient but it's convenient
with table as (
SELECT DATE, STATUS, TITLE, ROW_NUMBER()
OVER (PARTITION BY DATE, STATUS, TITLE ORDER BY QUANTITY ASC) AS Row_Num
FROM TABLE)
select *
from table t
join select(
max(Row_Num) as Row_Num
,DATE
,STATUS
,TITLE
from table
group by date, status, title) t2
on t2.Row_Num = t.Row_Num and t2
and t2.date = t.date
and t2.title = t.title
The lock
statement is translated to calls to the Enter
and Exit
methods of Monitor
.
The lock
statement will wait indefinitely for the locking object to be released.
To minimize drift more easily, use:
while :; do sleep 1m & some-command; wait; done
there will still be a tiny amount of drift due to bash's time to run the loop structure and the sleep command to actually execute.
hint: ':' evals to 0 ie true.
By default mysqldump
always creates the CREATE DATABASE IF NOT EXISTS db_name;
statement at the beginning of the dump file.
[EDIT] Few things about the mysqldump
file and it's options:
--all-databases
, -A
Dump all tables in all databases. This is the same as using the --databases
option and naming all the databases on the command line.
--add-drop-database
Add a DROP DATABASE
statement before each CREATE DATABASE
statement. This option is typically used in conjunction with the --all-databases
or --databases
option because no CREATE DATABASE
statements are written unless one of those options is specified.
--databases
, -B
Dump several databases. Normally, mysqldump
treats the first name argument on the command line as a database name and following names as table names. With this option, it treats all name arguments as database names. CREATE DATABASE
and USE
statements are included in the output before each new database.
--no-create-db
, -n
This option suppresses the CREATE DATABASE
statements that are otherwise included in the output if the --databases
or --all-databases
option is given.
Some time ago, there was similar question actually asking about not having such statement on the beginning of the file (for XML file). Link to that question is here.
So to answer your question:
--add-drop-database
option in your mysqldump
statement.--databases
or --all-databases
and the CREATE DATABASE
syntax will be added
automaticallyMore information at MySQL Reference Manual
You can create a variable with an application scope
In general it would be something like this:
if(test != "A" && test != "B")
You should probably read up on JavaScript logical operators.
Set-ExecutionPolicy Unrestricted -Scope CurrentUser
This will set the execution policy for the current user (stored in HKEY_CURRENT_USER) rather than the local machine (HKEY_LOCAL_MACHINE). This is useful if you don't have administrative control over the computer.
$(selector).change()
Longer slower alternative, better for abstraction.
$(selector).trigger("change")
The best solution I've found so far, that does not involve hard coding heights and breakpoints is to add an extra <nav...
tag to the markup.
<nav class="navbar navbar-expand-md" aria-hidden="true">
<a class="navbar-brand" href="#">Navbar</a>
</nav>
<nav class="navbar navbar-expand-md navbar-dark bg-dark fixed-top">
<a class="navbar-brand" href="#">Navbar</a>
By doing it this way the @media
breakpoints are identical, the height is identical (provided your navbar-brand
is the tallest object in the navbar
but you can easily substitute another element in the non fixed-top
navbar.
Where this fails is with screen readers which will now present 2 navbar-brand
elements. This points at the need for a not-for-sr
class to prevent that element from showing up for screen readers. However that class does not exist https://getbootstrap.com/docs/4.0/utilities/screenreaders/
I've tried to compensate for the screen reader issue with aria-hidden="true"
but https://www.accessibility-developer-guide.com/examples/sensible-aria-usage/hidden/ seems to indicate this will probably not work when the screen reader is in focus mode which is of course the only time you actually need it to work...
This is a pretty old question, and while looking for Git libraries, I found one that was made this year (2013) called Gittle.
It worked great for me (where the others I tried were flaky), and seems to cover most of the common actions.
Some examples from the README:
from gittle import Gittle
# Clone a repository
repo_path = '/tmp/gittle_bare'
repo_url = 'git://github.com/FriendCode/gittle.git'
repo = Gittle.clone(repo_url, repo_path)
# Stage multiple files
repo.stage(['other1.txt', 'other2.txt'])
# Do the commit
repo.commit(name="Samy Pesse", email="[email protected]", message="This is a commit")
# Authentication with RSA private key
key_file = open('/Users/Me/keys/rsa/private_rsa')
repo.auth(pkey=key_file)
# Do push
repo.push()
You can convert Map
to JSON
using Jackson as follows:
Map<String,String> payload = new HashMap<>();
payload.put("key1","value1");
payload.put("key2","value2");
String json = new ObjectMapper().writeValueAsString(payload);
System.out.println(json);
You can refer to following link for which features are supported in particular version of compiler. It has an exhaustive list of feature support in compiler. Looks GCC follows standard closely and implements before any other compiler.
Regarding your question you can compile using
g++ -std=c++11
for C++11 g++ -std=c++14
for C++14g++ -std=c++17
for C++17g++ -std=c++2a
for C++20, although all features of C++20 are not yet supported refer this link for feature support list in GCC.The list changes pretty fast, keep an eye on the list, if you are waiting for particular feature to be supported.
I did as how moplin mentioned .But in my case service send the JWT in response headers ,as a value under the key "Authorization".
Authorization ?Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJpbWFsIiwiZXhwIjoxNDk4OTIwOTEyfQ.dYEbf4x5TGr_kTtwywKPI2S-xYhsp5RIIBdOa_wl9soqaFkUUKfy73kaMAv_c-6cxTAqBwtskOfr-Gm3QI0gpQ
What I did was ,make a Global variable in postman as
key->jwt
value->blahblah
in login request->Tests Tab, add
postman.clearGlobalVariable("jwt");
postman.setGlobalVariable("jwt", postman.getResponseHeader("Authorization"));
in other requests select the Headers tab and give
key->Authorization
value->{{jwt}}
You need to use Arrow function ()=>
ES6 feature to preserve this
context within setTimeout
.
// var that = this; // no need of this line
this.messageSuccess = true;
setTimeout(()=>{ //<<<---using ()=> syntax
this.messageSuccess = false;
}, 3000);
You can use <<
to append to a string in-place.
s = "foo"
old_id = s.object_id
s << "bar"
s #=> "foobar"
s.object_id == old_id #=> true
here is a useful gist from lfmingo
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
Request request = original.newBuilder()
.header("User-Agent", "Your-App-Name")
.header("Accept", "application/vnd.yourapi.v1.full+json")
.method(original.method(), original.body())
.build();
return chain.proceed(request);
}
}
OkHttpClient client = httpClient.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
The following is also working for me:
ssh <user>@<host> "cat <filepath>"|pbcopy
String content = "";
char character;
if(Serial.available() >0){
//reset this variable!
content = "";
//make string from chars
while(Serial.available()>0) {
character = Serial.read();
content.concat(character);
}
//send back
Serial.print("#");
Serial.print(content);
Serial.print("#");
Serial.flush();
}
Extracting the Year say from ['2018-03-04']
df['Year'] = pd.DatetimeIndex(df['date']).year
The df['Year'] creates a new column. While if you want to extract the month just use .month
You should never use the unidirectional @OneToMany
annotation because:
Now, in your first example, both sides are owning the association, and this is bad.
While the @JoinColumn
would let the @OneToMany
side in charge of the association, it's definitely not the best choice. Therefore, always use the mappedBy
attribute on the @OneToMany
side.
public class User{
@OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
public List<APost> aPosts;
@OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
public List<BPost> bPosts;
}
public class BPost extends Post {
@ManyToOne(fetch=FetchType.LAZY)
public User user;
}
public class APost extends Post {
@ManyToOne(fetch=FetchType.LAZY)
public User user;
}
This problem usually occurs while cloning large repos. If git clone http://github.com/large-repository --depth 1
does not work on windows cmd. Try running the command in windows powershell.
int = 4 byte (fixed irrespective size of the architect) NSInteger = depend upon size of the architect(e.g. for 4 byte architect = 4 byte NSInteger size)
You should consider svcutil (svcutil question)
Both xsd.exe and svcutil operate on the XML schema file (.xsd). Your XML must conform to a schema file to be used by either of these two tools.
Note that various 3rd party tools also exist for this.
For me, I solved it this way:
rm .git/refs/remotes/origin/master
git fetch
After that I get this message from github.
There is no tracking information for the current branch
So next I did to fix this was:
git branch --set-upstream-to=origin/master master
git pull
The QDate class of PyQt4 has an addmonths function.
>>>from PyQt4.QtCore import QDate
>>>dt = QDate(2009,12,31)
>>>required = dt.addMonths(6)
>>>required
PyQt4.QtCore.QDate(2010, 6, 30)
>>>required.toPyDate()
datetime.date(2010, 6, 30)
Those script tags are a common way to implement templating functionality (like in PHP) but on the client side.
By setting the type to "text/template", it's not a script that the browser can understand, and so the browser will simply ignore it. This allows you to put anything in there, which can then be extracted later and used by a templating library to generate HTML snippets.
Backbone doesn't force you to use any particular templating library - there are quite a few out there: Mustache, Haml, Eco,Google Closure template, and so on (the one used in the example you linked to is underscore.js). These will use their own syntax for you to write within those script tags.
You can map JSON to specific class in Groovy using as
operator:
import groovy.json.JsonSlurper
String json = '''
{
"name": "John",
"age": 20
}
'''
def person = new JsonSlurper().parseText(json) as Person
with(person) {
assert name == 'John'
assert age == 20
}
RFC6648 recommends that you assume that your custom header "might become standardized, public, commonly deployed, or usable across multiple implementations." Therefore, it recommends not to prefix it with "X-" or similar constructs.
However, there is an exception "when it is extremely unlikely that [your header] will ever be standardized." For such "implementation-specific and private-use" headers, the RFC says a namespace such as a vendor prefix is justified.
class Hash
def to_params
params = ''
stack = []
each do |k, v|
if v.is_a?(Hash)
stack << [k,v]
elsif v.is_a?(Array)
stack << [k,Hash.from_array(v)]
else
params << "#{k}=#{v}&"
end
end
stack.each do |parent, hash|
hash.each do |k, v|
if v.is_a?(Hash)
stack << ["#{parent}[#{k}]", v]
else
params << "#{parent}[#{k}]=#{v}&"
end
end
end
params.chop!
params
end
def self.from_array(array = [])
h = Hash.new
array.size.times do |t|
h[t] = array[t]
end
h
end
end
A simple way to use modals is with eModal!
Ex from github:
<script src="//rawgit.com/saribe/eModal/master/dist/eModal.min.js"></script>
use eModal to display a modal for alert, ajax, prompt or confirm
// Display an alert modal with default title (Attention)
eModal.ajax('your/url.html');
$(document).ready(function () {/* activate scroll spy menu */_x000D_
_x000D_
var iconPrefix = '.glyphicon-';_x000D_
_x000D_
_x000D_
$(iconPrefix + 'cloud').click(ajaxDemo);_x000D_
$(iconPrefix + 'comment').click(alertDemo);_x000D_
$(iconPrefix + 'ok').click(confirmDemo);_x000D_
$(iconPrefix + 'pencil').click(promptDemo);_x000D_
$(iconPrefix + 'screenshot').click(iframeDemo);_x000D_
///////////////////* Implementation *///////////////////_x000D_
_x000D_
// Demos_x000D_
function ajaxDemo() {_x000D_
var title = 'Ajax modal';_x000D_
var params = {_x000D_
buttons: [_x000D_
{ text: 'Close', close: true, style: 'danger' },_x000D_
{ text: 'New content', close: false, style: 'success', click: ajaxDemo }_x000D_
],_x000D_
size: eModal.size.lg,_x000D_
title: title,_x000D_
url: 'http://maispc.com/app/proxy.php?url=http://loripsum.net/api/' + Math.floor((Math.random() * 7) + 1) + '/short/ul/bq/prude/code/decorete'_x000D_
};_x000D_
_x000D_
return eModal_x000D_
.ajax(params)_x000D_
.then(function () { alert('Ajax Request complete!!!!', title) });_x000D_
}_x000D_
_x000D_
function alertDemo() {_x000D_
var title = 'Alert modal';_x000D_
return eModal_x000D_
.alert('You welcome! Want clean code ?', title)_x000D_
.then(function () { alert('Alert modal is visible.', title); });_x000D_
}_x000D_
_x000D_
function confirmDemo() {_x000D_
var title = 'Confirm modal callback feedback';_x000D_
return eModal_x000D_
.confirm('It is simple enough?', 'Confirm modal')_x000D_
.then(function (/* DOM */) { alert('Thank you for your OK pressed!', title); })_x000D_
.fail(function (/*null*/) { alert('Thank you for your Cancel pressed!', title) });_x000D_
}_x000D_
_x000D_
function iframeDemo() {_x000D_
var title = 'Insiders';_x000D_
return eModal_x000D_
.iframe('https://www.youtube.com/embed/VTkvN51OPfI', title)_x000D_
.then(function () { alert('iFrame loaded!!!!', title) });_x000D_
}_x000D_
_x000D_
function promptDemo() {_x000D_
var title = 'Prompt modal callback feedback';_x000D_
return eModal_x000D_
.prompt({ size: eModal.size.sm, message: 'What\'s your name?', title: title })_x000D_
.then(function (input) { alert({ message: 'Hi ' + input + '!', title: title, imgURI: 'https://avatars0.githubusercontent.com/u/4276775?v=3&s=89' }) })_x000D_
.fail(function (/**/) { alert('Why don\'t you tell me your name?', title); });_x000D_
}_x000D_
_x000D_
//#endregion_x000D_
});
_x000D_
.fa{_x000D_
cursor:pointer;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="http://rawgit.com/saribe/eModal/master/dist/eModal.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootswatch/3.3.5/united/bootstrap.min.css" rel="stylesheet" >_x000D_
<link href="http//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet">_x000D_
_x000D_
<div class="row" itemprop="about">_x000D_
<div class="col-sm-1 text-center"></div>_x000D_
<div class="col-sm-2 text-center">_x000D_
<div class="row">_x000D_
<div class="col-sm-10 text-center">_x000D_
<h3>Ajax</h3>_x000D_
<p>You must get the message from a remote server? No problem!</p>_x000D_
<i class="glyphicon glyphicon-cloud fa-5x pointer" title="Try me!"></i>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="col-sm-2 text-center">_x000D_
<div class="row">_x000D_
<div class="col-sm-10 text-center">_x000D_
<h3>Alert</h3>_x000D_
<p>Traditional alert box. Using only text or a lot of magic!?</p>_x000D_
<i class="glyphicon glyphicon-comment fa-5x pointer" title="Try me!"></i>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div class="col-sm-2 text-center">_x000D_
<div class="row">_x000D_
<div class="col-sm-10 text-center">_x000D_
<h3>Confirm</h3>_x000D_
<p>Get an okay from user, has never been so simple and clean!</p>_x000D_
<i class="glyphicon glyphicon-ok fa-5x pointer" title="Try me!"></i>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="col-sm-2 text-center">_x000D_
<div class="row">_x000D_
<div class="col-sm-10 text-center">_x000D_
<h3>Prompt</h3>_x000D_
<p>Do you have a question for the user? We take care of it...</p>_x000D_
<i class="glyphicon glyphicon-pencil fa-5x pointer" title="Try me!"></i>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="col-sm-2 text-center">_x000D_
<div class="row">_x000D_
<div class="col-sm-10 text-center">_x000D_
<h3>iFrame</h3>_x000D_
<p>IFrames are hard to deal with it? We don't think so!</p>_x000D_
<i class="glyphicon glyphicon-screenshot fa-5x pointer" title="Try me!"></i>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="col-sm-1 text-center"></div>_x000D_
</div>
_x000D_
If you're using a wrapper layer (like Kitchen CI) and you're running a 32b host, you'll have to preempt the installation of Vagrant boxes. Their default provider is the opscode "family" of binaries.
So before kitchen create default-ubuntu-1204
make sure you use:
vagrant box add default-ubuntu-1204 http://opscode-vm-bento.s3.amazonaws.com/vagrant/virtualbox/opscode_ubuntu-12.04-i386_chef-provisionerless.box
for using the 32b image if your host doesn't support word size virtualization
Once java-8 is out (March 2014) you'll be able to use streams:
int sum = IntStream.of(a).sum();
or even
int sum = IntStream.of(a).parallel().sum();
My approach was similar to @SoftwareFactor, but different, perhaps because I'm running a different OS, Windows Server 2012. These steps worked for me.
Control Panel
> System and Security
> Administrative Tools
> Services
,
right-click SQL Server Browser
> Properties
> General tab
,
change Startup
type to Automatic
,
click Apply
button,
then click Start
button in Service Status
area.
I have had the same error. I added dependency on pom.xml (I am working with Maven)
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.12.1</version>
</dependency>
I started trying with version 2.9.0, then I found a different error (com/fasterxml/jackson/core/exc/InputCoercionException) then I try different versions until all errors were solved with version 2.12.1
This is not answering the question itself, but I found this question searching for the solution to convert a string to symbol and use it on a hash.
hsh = Hash.new
str_to_symbol = "Book Author Title".downcase.gsub(/\s+/, "_").to_sym
hsh[str_to_symbol] = 10
p hsh
# => {book_author_title: 10}
Hope it helps someone like me!
Here is the rub:
::selection { background: #ffb7b7; /* WebKit/Blink Browsers / } ::-moz-selection { background: #ffb7b7; / Gecko Browsers */ }Within the selection selector, color and background are the only properties that work. What you can do for some extra flair, is change the selection color for different paragraphs or different sections of the page.
All I did was use different selection color for paragraphs with different classes:
p.red::selection { background: #ffb7b7; } p.red::-moz-selection { background: #ffb7b7; } p.blue::selection { background: #a8d1ff; } p.blue::-moz-selection { background: #a8d1ff; } p.yellow::selection { background: #fff2a8; } p.yellow::-moz-selection { background: #fff2a8; }Note how the selectors are not combined, even though >the style block is doing the same thing. It doesn't work if you combine them:
<pre>/* Combining like this WILL NOT WORK */
p.yellow::selection,
p.yellow::-moz-selection {
background: #fff2a8;
}</pre>
That's because browsers ignore the entire selector if there is a part of it they don't understand or is invalid. There is some exceptions to this (IE 7?) but not in relation to these selectors.
I had this exact problem, except I couldn't use images and was not limited by browser support. This should be «on spec» and with luck start working everywhere eventually.
It uses layered rotated background layers to «cut out» a dropdown arrow, as pseudo-elements wouldn't work for the select element.
Edit: In this updated version I am using CSS variables and a tiny theming system.
:root {_x000D_
--radius: 2px;_x000D_
--baseFg: dimgray;_x000D_
--baseBg: white;_x000D_
--accentFg: #006fc2;_x000D_
--accentBg: #bae1ff;_x000D_
}_x000D_
_x000D_
.theme-pink {_x000D_
--radius: 2em;_x000D_
--baseFg: #c70062;_x000D_
--baseBg: #ffe3f1;_x000D_
--accentFg: #c70062;_x000D_
--accentBg: #ffaad4;_x000D_
}_x000D_
_x000D_
.theme-construction {_x000D_
--radius: 0;_x000D_
--baseFg: white;_x000D_
--baseBg: black;_x000D_
--accentFg: black;_x000D_
--accentBg: orange;_x000D_
}_x000D_
_x000D_
select {_x000D_
font: 400 12px/1.3 sans-serif;_x000D_
-webkit-appearance: none;_x000D_
appearance: none;_x000D_
color: var(--baseFg);_x000D_
border: 1px solid var(--baseFg);_x000D_
line-height: 1;_x000D_
outline: 0;_x000D_
padding: 0.65em 2.5em 0.55em 0.75em;_x000D_
border-radius: var(--radius);_x000D_
background-color: var(--baseBg);_x000D_
background-image: linear-gradient(var(--baseFg), var(--baseFg)),_x000D_
linear-gradient(-135deg, transparent 50%, var(--accentBg) 50%),_x000D_
linear-gradient(-225deg, transparent 50%, var(--accentBg) 50%),_x000D_
linear-gradient(var(--accentBg) 42%, var(--accentFg) 42%);_x000D_
background-repeat: no-repeat, no-repeat, no-repeat, no-repeat;_x000D_
background-size: 1px 100%, 20px 22px, 20px 22px, 20px 100%;_x000D_
background-position: right 20px center, right bottom, right bottom, right bottom; _x000D_
}_x000D_
_x000D_
select:hover {_x000D_
background-image: linear-gradient(var(--accentFg), var(--accentFg)),_x000D_
linear-gradient(-135deg, transparent 50%, var(--accentFg) 50%),_x000D_
linear-gradient(-225deg, transparent 50%, var(--accentFg) 50%),_x000D_
linear-gradient(var(--accentFg) 42%, var(--accentBg) 42%);_x000D_
}_x000D_
_x000D_
select:active {_x000D_
background-image: linear-gradient(var(--accentFg), var(--accentFg)),_x000D_
linear-gradient(-135deg, transparent 50%, var(--accentFg) 50%),_x000D_
linear-gradient(-225deg, transparent 50%, var(--accentFg) 50%),_x000D_
linear-gradient(var(--accentFg) 42%, var(--accentBg) 42%);_x000D_
color: var(--accentBg);_x000D_
border-color: var(--accentFg);_x000D_
background-color: var(--accentFg);_x000D_
}
_x000D_
<select>_x000D_
<option>So many options</option>_x000D_
<option>...</option>_x000D_
</select>_x000D_
_x000D_
<select class="theme-pink">_x000D_
<option>So many options</option>_x000D_
<option>...</option>_x000D_
</select>_x000D_
_x000D_
<select class="theme-construction">_x000D_
<option>So many options</option>_x000D_
<option>...</option>_x000D_
</select>
_x000D_
From the menu:
Build|Generate Signed APK
or
Build|Build APK
(the latter if you don't need a signed one to publish to the Play Store)
A one-liner (no essential difference to the answers above though):
document.body.appendChild(document.createElement('script')).src = 'source.js';
In my case, I have Java 14 and need Java 8.
I'm in a Arch Linux and has installed jdk8-openjdk jre8-openjdk
https://www.archlinux.org/packages/extra/x86_64/java8-openjdk/
For Debian users https://wiki.debian.org/Java, or Fedora https://docs.fedoraproject.org/en-US/quick-docs/installing-java/.
Install Java 8 (or desired version, in this case jdk8-openjdk jre8-openjdk
) using your package manager before doing the following steps.
# which java
/usr/bin/java
I can see all java files here are links to /usr/lib/jvm/default[something]
. This means that the java
command is linked to some specific version of java
executable.
# ls -l /usr/bin/java*
lrwxrwxrwx 1 root root 37 May 16 06:30 /usr/bin/java -> /usr/lib/jvm/default-runtime/bin/java
lrwxrwxrwx 1 root root 30 May 16 06:30 /usr/bin/javac -> /usr/lib/jvm/default/bin/javac
lrwxrwxrwx 1 root root 32 May 16 06:30 /usr/bin/javadoc -> /usr/lib/jvm/default/bin/javadoc
lrwxrwxrwx 1 root root 30 May 16 06:30 /usr/bin/javah -> /usr/lib/jvm/default/bin/javah
lrwxrwxrwx 1 root root 30 May 16 06:30 /usr/bin/javap -> /usr/lib/jvm/default/bin/javap
default
and default-runtime
Here I could see the default version was linked to 14 (unique installed version).
# cd /usr/lib/jvm
# ls -l
lrwxrwxrwx 1 root root 14 Aug 8 20:44 default -> java-14-openjdk
lrwxrwxrwx 1 root root 14 Aug 8 20:44 default-runtime -> java-14-openjdk
drwxr-xr-x 7 root root 4096 Jul 19 22:38 java-14-openjdk
drwxr-xr-x 6 root root 4096 Aug 8 20:42 java-8-openjdk
First, remove the existing default
and default-runtime
which linked to java-14 version.
# rm default default-runtime
Then, create new links to the desired version (in this case, java-8).
# link -s java-8-openjdk default
# link -s java-8-openjdk default-runtime
The strategy is to make links to the desired version of software (java8 in this case) using ln -s
above. Then, this links are linked to the binaries inside the java bin directory (without changing the $PATH
environment variable!)
Or you might be wanted to change the Java version using archlinux-java
command instead with more safely approach: https://wiki.archlinux.org/index.php/Java
public class Test9 {
static class Student {
String stud_id;
String stud_name;
String stud_location;
public Student(String stud_id, String stud_name, String stud_location) {
super();
this.stud_id = stud_id;
this.stud_name = stud_name;
this.stud_location = stud_location;
}
public String getStud_id() {
return stud_id;
}
public void setStud_id(String stud_id) {
this.stud_id = stud_id;
}
public String getStud_name() {
return stud_name;
}
public void setStud_name(String stud_name) {
this.stud_name = stud_name;
}
public String getStud_location() {
return stud_location;
}
public void setStud_location(String stud_location) {
this.stud_location = stud_location;
}
@Override
public String toString() {
return " [stud_id=" + stud_id + ", stud_name=" + stud_name + "]";
}
}
public static void main(String[] args) {
List<Student> list = new ArrayList<Student>();
list.add(new Student("1726", "John Easton", "Lancaster"));
list.add(new Student("4321", "Max Carrados", "London"));
list.add(new Student("2234", "Andrew Lewis", "Lancaster"));
list.add(new Student("5223", "Michael Benson", "Leeds"));
list.add(new Student("5225", "Sanath Jayasuriya", "Leeds"));
list.add(new Student("7765", "Samuael Vatican", "California"));
list.add(new Student("3442", "Mark Farley", "Ladykirk"));
list.add(new Student("3443", "Alex Stuart", "Ladykirk"));
list.add(new Student("4321", "Michael Stuart", "California"));
Map<String, List<Student>> map1 =
list
.stream()
.sorted(Comparator.comparing(Student::getStud_id)
.thenComparing(Student::getStud_name)
.thenComparing(Student::getStud_location)
)
.collect(Collectors.groupingBy(
ch -> ch.stud_location
));
System.out.println(map1);
/*
Output :
{Ladykirk=[ [stud_id=3442, stud_name=Mark Farley],
[stud_id=3443, stud_name=Alex Stuart]],
Leeds=[ [stud_id=5223, stud_name=Michael Benson],
[stud_id=5225, stud_name=Sanath Jayasuriya]],
London=[ [stud_id=4321, stud_name=Max Carrados]],
Lancaster=[ [stud_id=1726, stud_name=John Easton],
[stud_id=2234, stud_name=Andrew Lewis]],
California=[ [stud_id=4321, stud_name=Michael Stuart],
[stud_id=7765, stud_name=Samuael Vatican]]}
*/
}// main
}
You can use this for getting current and log times:
#!/bin/bash
log="log_file_name"
while read line
do
current_hours=`date | awk 'BEGIN{FS="[ :]+"}; {print $4}'`
current_minutes=`date | awk 'BEGIN{FS="[ :]+"}; {print $5}'`
current_seconds=`date | awk 'BEGIN{FS="[ :]+"}; {print $6}'`
log_file_hours=`echo $line | awk 'BEGIN{FS="[ [/:]+"}; {print $7}'`
log_file_minutes=`echo $line | awk 'BEGIN{FS="[ [/:]+"}; {print $8}'`
log_file_seconds=`echo $line | awk 'BEGIN{FS="[ [/:]+"}; {print $9}'`
done < $log
And compare log_file_*
and current_*
variables.
3 easy steps to run your PHP program is:
The easiest way is to install MAMP!
Do a 2-minute setup of MAMP.
Open the localhost server in your browser at the created port to see your program up and runing!
I deleted the C:\inetpub folder and reinstalled IIS which recreated the default website and settings.
Here is a solution based on the powerful but poorly documented logging.config.dictConfig
method.
Instead of sending every log message to stdout
, it sends messages with log level ERROR
and higher to stderr
and everything else to stdout
.
This can be useful if other parts of the system are listening to stderr
or stdout
.
import logging
import logging.config
import sys
class _ExcludeErrorsFilter(logging.Filter):
def filter(self, record):
"""Only returns log messages with log level below ERROR (numeric value: 40)."""
return record.levelno < 40
config = {
'version': 1,
'filters': {
'exclude_errors': {
'()': _ExcludeErrorsFilter
}
},
'formatters': {
# Modify log message format here or replace with your custom formatter class
'my_formatter': {
'format': '(%(process)d) %(asctime)s %(name)s (line %(lineno)s) | %(levelname)s %(message)s'
}
},
'handlers': {
'console_stderr': {
# Sends log messages with log level ERROR or higher to stderr
'class': 'logging.StreamHandler',
'level': 'ERROR',
'formatter': 'my_formatter',
'stream': sys.stderr
},
'console_stdout': {
# Sends log messages with log level lower than ERROR to stdout
'class': 'logging.StreamHandler',
'level': 'DEBUG',
'formatter': 'my_formatter',
'filters': ['exclude_errors'],
'stream': sys.stdout
},
'file': {
# Sends all log messages to a file
'class': 'logging.FileHandler',
'level': 'DEBUG',
'formatter': 'my_formatter',
'filename': 'my.log',
'encoding': 'utf8'
}
},
'root': {
# In general, this should be kept at 'NOTSET'.
# Otherwise it would interfere with the log levels set for each handler.
'level': 'NOTSET',
'handlers': ['console_stderr', 'console_stdout', 'file']
},
}
logging.config.dictConfig(config)
$msg="You Enter Wrong Username OR Password"; $responso=json_encode($msg);
echo "{\"status\" : \"400\", \"responce\" : \"603\", \"message\" : \"You Enter Wrong Username OR Password\", \"feed\":".str_replace("<p>","",$responso). "}";
There are two built-in functions that help you identify the type of an object. You can use type()
if you need the exact type of an object, and isinstance()
to check an object’s type against something. Usually, you want to use isinstance()
most of the times since it is very robust and also supports type inheritance.
To get the actual type of an object, you use the built-in type()
function. Passing an object as the only parameter will return the type object of that object:
>>> type([]) is list
True
>>> type({}) is dict
True
>>> type('') is str
True
>>> type(0) is int
True
This of course also works for custom types:
>>> class Test1 (object):
pass
>>> class Test2 (Test1):
pass
>>> a = Test1()
>>> b = Test2()
>>> type(a) is Test1
True
>>> type(b) is Test2
True
Note that type()
will only return the immediate type of the object, but won’t be able to tell you about type inheritance.
>>> type(b) is Test1
False
To cover that, you should use the isinstance
function. This of course also works for built-in types:
>>> isinstance(b, Test1)
True
>>> isinstance(b, Test2)
True
>>> isinstance(a, Test1)
True
>>> isinstance(a, Test2)
False
>>> isinstance([], list)
True
>>> isinstance({}, dict)
True
isinstance()
is usually the preferred way to ensure the type of an object because it will also accept derived types. So unless you actually need the type object (for whatever reason), using isinstance()
is preferred over type()
.
The second parameter of isinstance()
also accepts a tuple of types, so it’s possible to check for multiple types at once. isinstance
will then return true, if the object is of any of those types:
>>> isinstance([], (tuple, list, set))
True
I've forgot to start MongoDB at all. Go to separate tab in terminal and type:
sudo service mongod start
React Native .toUpperCase() function works fine in a string but if you used the numbers
or other non-string data types
, it doesn't work. The error
will have occurred.
Below Two are string properties:
<Text>{props.complexity.toUpperCase()}</Text>
<Text>{props.affordability.toUpperCase()}</Text>
All answers above are correct, However People who are coming from other programming language. The easiest approach to follow will be.
variable = 1
print("length " + format(variable))
XAMPP should have come with a "fake" sendmail program. In that case, you can use sendmail as well:
[mail function]
; For Win32 only.
; http://php.net/smtp
;SMTP = localhost
; http://php.net/smtp-port
;smtp_port = 25
; For Win32 only.
; http://php.net/sendmail-from
;sendmail_from = [email protected]
; For Unix only. You may supply arguments as well (default: "sendmail -t -i").
; http://php.net/sendmail-path
sendmail_path = "C:/xampp/sendmail/sendmail.exe -t -i"
Sendmail should have a sendmail.ini
with it; it should be configured as so:
# Example for a user configuration file
# Set default values for all following accounts.
defaults
logfile "C:\xampp\sendmail\sendmail.log"
# Mercury
#account Mercury
#host localhost
#from postmaster@localhost
#auth off
# A freemail service example
account ACCOUNTNAME_HERE
tls on
tls_certcheck off
host smtp.gmail.com
from EMAIL_HERE
auth on
user EMAIL_HERE
password PASSWORD_HERE
# Set a default account
account default : ACCOUNTNAME_HERE
Of course, replace ACCOUNTNAME_HERE with an arbitrary account name, replace EMAIL_HERE with a valid email (such as a Gmail or Hotmail), and replace PASSWORD_HERE with the password to your email. Now, you should be able to send mail. Remember to restart Apache (from the control panel or the batch files) to allow the changes to PHP to work.
The spaces are significant. You created a variable named 'location '
with a value of
' "bob"'
. Note - enclosing single quotes were added to show location of space.
If you want quotes in your value, then your code should look like
set location="bob"
If you don't want quotes, then your code should look like
set location=bob
Or better yet
set "location=bob"
The last syntax prevents inadvertent trailing spaces from getting in the value, and also protects against special characters like &
|
etc.
Re: craigts's response, for anyone having trouble with using either False or None parameters for index_col, such as in cases where you're trying to get rid of a range index, you can instead use an integer to specify the column you want to use as the index. For example:
df = pd.read_csv('file.csv', index_col=0)
The above will set the first column as the index (and not add a range index in my "common case").
Given the popularity of this answer, I thought i'd add some context/ a demo:
# Setting up the dummy data
In [1]: df = pd.DataFrame({"A":[1, 2, 3], "B":[4, 5, 6]})
In [2]: df
Out[2]:
A B
0 1 4
1 2 5
2 3 6
In [3]: df.to_csv('file.csv', index=None)
File[3]:
A B
1 4
2 5
3 6
Reading without index_col or with None/False will all result in a range index:
In [4]: pd.read_csv('file.csv')
Out[4]:
A B
0 1 4
1 2 5
2 3 6
# Note that this is the default behavior, so the same as In [4]
In [5]: pd.read_csv('file.csv', index_col=None)
Out[5]:
A B
0 1 4
1 2 5
2 3 6
In [6]: pd.read_csv('file.csv', index_col=False)
Out[6]:
A B
0 1 4
1 2 5
2 3 6
However, if we specify that "A" (the 0th column) is actually the index, we can avoid the range index:
In [7]: pd.read_csv('file.csv', index_col=0)
Out[7]:
B
A
1 4
2 5
3 6
A literally insane answer, but if you have some kind of replication system set up (for a system with a billion rows, I hope you do), you can use a rough-estimator (like MAX(pk)
), divide that value by the number of slaves you have, run several queries in parallel.
For the most part, you'd partition the queries across slaves based on the best key (or the primary key I guess), in such a way (we're going to use 250000000 as our Rows / Slaves):
-- First slave
SELECT COUNT(pk) FROM t WHERE pk < 250000000
-- Ith slave where 2 <= I <= N - 1
SELECT COUNT(pk) FROM t WHERE pk >= I*250000000 and pk < (I+1)*250000000
-- Last slave
SELECT COUNT(pk) FROM t WHERE pk > (N-1)*250000000
But you need SQL only. What a bust. Ok, so let's say you're a sadomasochist. On the master (or closest slave) you'd most likely need to create a table for this:
CREATE TABLE counter_table (minpk integer, maxpk integer, cnt integer, slaveid integer)
So instead of only having the selects running in your slaves, you'd have to do an insert, akin to this:
INSERT INTO counter_table VALUES (I*25000000, (I+1)*250000000, (SELECT COUNT(pk) FROM ... ), @@SLAVE_ID)
You may run into issues with slaves writing to a table on master. You may need to get even more sadis- I mean, creative:
-- A table per slave!
INSERT INTO counter_table_slave_I VALUES (...)
You should in the end have a slave that exists last in the path traversed by the replication graph, relative to the first slave. That slave should now have all other counter values, and should have its own values. But by the time you've finished, there probably are rows added, so you'd have to insert another one compensating for the recorded max pk in your counter_table and the current max pk.
At that point, you'd have to do an aggregate function to figure out what the total rows are, but that's easier since you'd be running it on at most the "number of slaves you have and change" rows.
If you're in the situation where you have separate tables in the slaves, you can UNION
to get all the rows you need.
SELECT SUM(cnt) FROM (
SELECT * FROM counter_table_slave_1
UNION
SELECT * FROM counter_table_slave_2
UNION
...
)
Or you know, be a bit less insane and migrate your data to a distributed processing system, or maybe use a Data Warehousing solution (which will give you awesome data crunching in the future too).
Do note, this does depend on how well your replication is set up. Since the primary bottleneck will most likely be persistent storage, if you have cruddy storage or poorly segregated data stores with heavy neighbor noise, this will probably run you slower than just waiting for a single SELECT COUNT(*) ...
But if you have good replication, then your speed gains should be directly related to the number or slaves. In fact, if it takes 10 minutes to run the counting query alone, and you have 8 slaves, you'd cut your time to less than a couple minutes. Maybe an hour to iron out the details of this solution.
Of course, you'd never really get an amazingly accurate answer since this distributed solving introduces a bit of time where rows can be deleted and inserted, but you can try to get a distributed lock of rows at the same instance and get a precise count of the rows in the table for a particular moment in time.
Actually, this seems impossible, since you're basically stuck with an SQL-only solution, and I don't think you're provided a mechanism to run a sharded and locked query across multiple slaves, instantly. Maybe if you had control of the replication log file... which means you'd literally be spinning up slaves for this purpose, which is no doubt slower than just running the count query on a single machine anyway.
So there's my two 2013 pennies.
This is the code to create dropdown in Angular 7, 8, 9
.html
file code
<div>
<label>Summary: </label>
<select (change)="SelectItem($event.target.value)" class="select">
<option value="0">--All--</option>
<option *ngFor="let item of items" value="{{item.Id.Value}}">
{{item.Name}}
</option>
</select>
</div>
.ts
file code
SelectItem(filterVal: any)
{
var id=filterVal;
//code
}
items
is an array which should be initialized in .ts
file.
From iOS 8 we can use the new isOperatingSystemAtLeastVersion
method on NSProcessInfo
NSOperatingSystemVersion ios8_0_1 = (NSOperatingSystemVersion){8, 0, 1};
if ([[NSProcessInfo processInfo] isOperatingSystemAtLeastVersion:ios8_0_1]) {
// iOS 8.0.1 and above logic
} else {
// iOS 8.0.0 and below logic
}
Beware that this will crash on iOS 7, as the API didn't exist prior to iOS 8. If you're supporting iOS 7 and below, you can safely perform the check with
if ([NSProcessInfo instancesRespondToSelector:@selector(isOperatingSystemAtLeastVersion:)]) {
// conditionally check for any version >= iOS 8 using 'isOperatingSystemAtLeastVersion'
} else {
// we're on iOS 7 or below
}
For the sake of completeness, here's an alternative approach proposed by Apple itself in the iOS 7 UI Transition Guide, which involves checking the Foundation Framework version.
if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1) {
// Load resources for iOS 6.1 or earlier
} else {
// Load resources for iOS 7 or later
}
For this case: user signup form, user must choose a username that is not taken.
This means we have to create a customized validation rule, which will send async http request with remote server.
<input name="user_name" type="text" >
$("form").validate({
rules: {
'user_name': {
// here jquery validate will start a GET request, to
// /interface/users/is_username_valid?user_name=<input_value>
// the response should be "raw text", with content "true" or "false" only
remote: '/interface/users/is_username_valid'
},
},
class Interface::UsersController < ActionController::Base
def is_username_valid
render :text => !User.exists?(:user_name => params[:user_name])
end
end
position: fixed;
will solve your issue. As an example, review my implementation of a fixed message area overlay (populated programmatically):
#mess {
position: fixed;
background-color: black;
top: 20px;
right: 50px;
height: 10px;
width: 600px;
z-index: 1000;
}
And in the HTML
<body>
<div id="mess"></div>
<div id="data">
Much content goes here.
</div>
</body>
When #data
becomes longer tha the sceen, #mess
keeps its position on the screen, while #data
scrolls under it.
Here is a good solution:
FUNCTION comma_to_table(iv_raw IN VARCHAR2) RETURN dbms_utility.lname_array IS
ltab_lname dbms_utility.lname_array;
ln_len BINARY_INTEGER;
BEGIN
dbms_utility.comma_to_table(list => iv_raw
,tablen => ln_len
,tab => ltab_lname);
FOR i IN 1 .. ln_len LOOP
dbms_output.put_line('element ' || i || ' is ' || ltab_lname(i));
END LOOP;
RETURN ltab_lname;
END;
Source: CSV - comma separated values - and PL/SQL (link no longer valid)
If you don't want to alter the list:
List<Integer> list = Arrays.asList(array)
But if you want to modify it then you can use this:
List<Integer> list = new ArrayList<Integer>(Arrays.asList(ints));
Or just use java8 like the following:
List<Integer> list = Arrays.stream(ints).collect(Collectors.toList());
Java9 has introduced this method:
List<Integer> list = List.of(ints);
However, this will return an immutable list that you can't add to.
You need to do the following to make it mutable:
List<Integer> list = new ArrayList<Integer>(List.of(ints));
In the case of some programs, these errors are normal and should not be fixed.
I get these error messages when compiling the program phrap (for example). This program happens to contain code that modifies or replaces some built in functions, and when I include the appropriate header files to fix the warnings, GCC instead generates a bunch of errors. So fixing the warnings effectively breaks the build.
If you got the source as part of a distribution that should compile normally, the errors might be normal. Consult the documentation to be sure.
Take a look at this.
Change your query to:
SET @rank=0;
SELECT @rank:=@rank+1 AS rank, itemID, COUNT(*) as ordercount
FROM orders
GROUP BY itemID
ORDER BY ordercount DESC;
SELECT @rank;
The last select is your count.
Debug and Release are just labels for different solution configurations. You can add others if you want. A project I once worked on had one called "Debug Internal" which was used to turn on the in-house editing features of the application. You can see this if you go to Configuration Manager...
(it's on the Build
menu). You can find more information on MSDN Library under Configuration Manager Dialog Box.
Each solution configuration then consists of a bunch of project configurations. Again, these are just labels, this time for a collection of settings for your project. For example, our C++ library projects have project configurations called "Debug", "Debug_Unicode", "Debug_MT", etc.
The available settings depend on what type of project you're building. For a .NET project, it's a fairly small set: #define
s and a few other things. For a C++ project, you get a much bigger variety of things to tweak.
In general, though, you'll use "Debug" when you want your project to be built with the optimiser turned off, and when you want full debugging/symbol information included in your build (in the .PDB file, usually). You'll use "Release" when you want the optimiser turned on, and when you don't want full debugging information included.
I made my own way based on Caitlin Morris's answer for fetching all folowers and followings on Instagram. Just copy this code, paste in browser console and wait for a few seconds.
You need to use browser console from instagram.com tab to make it works.
let username = 'USERNAME'
let followers = [], followings = []
try {
let res = await fetch(`https://www.instagram.com/${username}/?__a=1`)
res = await res.json()
let userId = res.graphql.user.id
let after = null, has_next = true
while (has_next) {
await fetch(`https://www.instagram.com/graphql/query/?query_hash=c76146de99bb02f6415203be841dd25a&variables=` + encodeURIComponent(JSON.stringify({
id: userId,
include_reel: true,
fetch_mutual: true,
first: 50,
after: after
}))).then(res => res.json()).then(res => {
has_next = res.data.user.edge_followed_by.page_info.has_next_page
after = res.data.user.edge_followed_by.page_info.end_cursor
followers = followers.concat(res.data.user.edge_followed_by.edges.map(({node}) => {
return {
username: node.username,
full_name: node.full_name
}
}))
})
}
console.log('Followers', followers)
has_next = true
after = null
while (has_next) {
await fetch(`https://www.instagram.com/graphql/query/?query_hash=d04b0a864b4b54837c0d870b0e77e076&variables=` + encodeURIComponent(JSON.stringify({
id: userId,
include_reel: true,
fetch_mutual: true,
first: 50,
after: after
}))).then(res => res.json()).then(res => {
has_next = res.data.user.edge_follow.page_info.has_next_page
after = res.data.user.edge_follow.page_info.end_cursor
followings = followings.concat(res.data.user.edge_follow.edges.map(({node}) => {
return {
username: node.username,
full_name: node.full_name
}
}))
})
}
console.log('Followings', followings)
} catch (err) {
console.log('Invalid username')
}
Another useful tool is nmap (brew install nmap)
nmap --script ssl-enum-ciphers -p 443 google.com
Gives output
Starting Nmap 7.12 ( https://nmap.org ) at 2016-08-11 17:25 IDT
Nmap scan report for google.com (172.217.23.46)
Host is up (0.061s latency).
Other addresses for google.com (not scanned): 2a00:1450:4009:80a::200e
PORT STATE SERVICE
443/tcp open https
| ssl-enum-ciphers:
| TLSv1.0:
| ciphers:
| TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA (secp256r1) - A
| TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA (secp256r1) - A
| TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA (secp256r1) - A
| TLS_RSA_WITH_AES_128_CBC_SHA (rsa 2048) - A
| TLS_RSA_WITH_3DES_EDE_CBC_SHA (rsa 2048) - C
| TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA (secp256r1) - A
| TLS_RSA_WITH_AES_256_CBC_SHA (rsa 2048) - A
| compressors:
| NULL
| cipher preference: server
| TLSv1.1:
| ciphers:
| TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA (secp256r1) - A
| TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA (secp256r1) - A
| TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA (secp256r1) - A
| TLS_RSA_WITH_AES_128_CBC_SHA (rsa 2048) - A
| TLS_RSA_WITH_3DES_EDE_CBC_SHA (rsa 2048) - C
| TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA (secp256r1) - A
| TLS_RSA_WITH_AES_256_CBC_SHA (rsa 2048) - A
| compressors:
| NULL
| cipher preference: server
| TLSv1.2:
| ciphers:
| TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA (secp256r1) - A
| TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 (secp256r1) - A
| TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 (secp256r1) - A
| TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA (secp256r1) - A
| TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 (secp256r1) - A
| TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 (secp256r1) - A
| TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 (secp256r1) - A
| TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA (secp256r1) - A
| TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 (secp256r1) - A
| TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 (secp256r1) - A
| TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA (secp256r1) - A
| TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 (secp256r1) - A
| TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (secp256r1) - A
| TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 (secp256r1) - A
| TLS_RSA_WITH_3DES_EDE_CBC_SHA (rsa 2048) - C
| TLS_RSA_WITH_AES_128_CBC_SHA (rsa 2048) - A
| TLS_RSA_WITH_AES_128_CBC_SHA256 (rsa 2048) - A
| TLS_RSA_WITH_AES_128_GCM_SHA256 (rsa 2048) - A
| TLS_RSA_WITH_AES_256_CBC_SHA (rsa 2048) - A
| TLS_RSA_WITH_AES_256_CBC_SHA256 (rsa 2048) - A
| TLS_RSA_WITH_AES_256_GCM_SHA384 (rsa 2048) - A
| compressors:
| NULL
| cipher preference: client
|_ least strength: C
Nmap done: 1 IP address (1 host up) scanned in 5.48 seconds
Here is a method that returns the image dimensions:
from PIL import Image
import os
def get_image_dimensions(imagefile):
"""
Helper function that returns the image dimentions
:param: imagefile str (path to image)
:return dict (of the form: {width:<int>, height=<int>, size_bytes=<size_bytes>)
"""
# Inline import for PIL because it is not a common library
with Image.open(imagefile) as img:
# Calculate the width and hight of an image
width, height = img.size
# calculat ethe size in bytes
size_bytes = os.path.getsize(imagefile)
return dict(width=width, height=height, size_bytes=size_bytes)
Use a regular expression of the form: \w-\d+ where a \w represents a word and \d represents a digit. They won't work out of the box, so play around. Try this.
Better use PHP_EOL ("End Of Line") instead. It's cross-platform.
E.g.:
$unit1 = 'paragrahp1';
$unit2 = 'paragrahp2';
echo '<p>' . $unit1 . '</p>' . PHP_EOL;
echo '<p>' . $unit2 . '</p>';
If some of your services are balking into ulimits, it's sometimes easier to put appropriate commands into service's init-script. For example, when Apache is reporting
[alert] (11)Resource temporarily unavailable: apr_thread_create: unable to create worker thread
Try to put ulimit -s unlimited
into /etc/init.d/httpd
. This does not require a server reboot.
I've found String.fromCharCode(13, 10)
helpful when using view engines.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCharCode
This creates a string with the actual newline characters in it and so forces the view engine to output a newline rather than an escaped version. Eg: Using NodeJS EJS view engine - This is a simple example in which any \n should be replaced:
viewHelper.js
exports.replaceNewline = function(input) {
var newline = String.fromCharCode(13, 10);
return input.replaceAll('\\n', newline);
}
EJS
<textarea><%- viewHelper.replaceNewline("Blah\nblah\nblah") %></textarea>
Renders
<textarea>Blah
blah
blah</textarea>
replaceAll:
String.prototype.replaceAll = function (find, replace) {
var result = this;
do {
var split = result.split(find);
result = split.join(replace);
} while (split.length > 1);
return result;
};
Found the answer in How to lay out Views in RelativeLayout programmatically?
We should explicitly set id's using setId(). Only then, RIGHT_OF rules make sense.
Another mistake I did is, reusing the layoutparams object between the controls. We should create new object for each control
((1,2,3,4),
(5,6,7,8),
(9,0,1,2))
Using tuples instead of lists makes it marginally harder to change the data structure in unwanted ways.
If you are going to do extensive use of those, you are best off wrapping a true number array in a class, so you can define methods and properties on them. (Or, you could NumPy, SciPy, ... if you are going to do your processing with those libraries.)
i got this problem "gpg-no-valid-openpgp-data-found" and solve it with the following first i open browser and paste https://pkg.jenkins.io/debian/jenkins-ci.org.key then i download the key in Downloads folder then cd /Downloads/ then sudo apt-key add jenkins-ci.org.key if Appear "OK" then you success to add the key :)
If you know you're always going to use bash, it's much easier to always use the double bracket conditional compound command [[ ... ]]
, instead of the Posix-compatible single bracket version [ ... ]
. Inside a [[ ... ]]
compound, word-splitting and pathname expansion are not applied to words, so you can rely on
if [[ $aug1 == "and" ]];
to compare the value of $aug1
with the string and
.
If you use [ ... ]
, you always need to remember to double quote variables like this:
if [ "$aug1" = "and" ];
If you don't quote the variable expansion and the variable is undefined or empty, it vanishes from the scene of the crime, leaving only
if [ = "and" ];
which is not a valid syntax. (It would also fail with a different error message if $aug1
included white space or shell metacharacters.)
The modern [[
operator has lots of other nice features, including regular expression matching.
I do this with a one liner:
val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, uri)
Which in the onActivityResult looks like:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_IMAGE_PICKER ) {
data?.data?.let { imgUri: Uri ->
val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, imgUri)
}
}
}
<select name="country" formControlName="country" id="country"
class="formcontrol form-control-element" [(ngModel)]="country">
<option value="90">Turkey</option>
<option value="1">USA</option>
<option value="30">Greece</option>
</select>
name="country"
formControlName="country"
[(ngModel)]="country"
Those are the three things need to use ngModel inside a formGroup directive.
Note that same name should be used.
This is an old thread, but I'm responding because it still appears high in the list of search results. Now that the future has arrived, you can use the :nth-child pseudo-selector.
p:nth-child(1) { color: blue; }
p.myclass1:nth-child(1) { color: red; }
p.myclass2:nth-child(1) { color: green; }
The :nth-child pseudo-selector is powerful - the parentheses accept formulas as well as numbers.
More here: https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child
Dumb solution: Connecting them through a named pipe (mkfifo). Then the command can be run second.
mkfifo pipe
tee out.txt < pipe &
command > pipe
echo $?
To blank it:
myObject["myVar"]=null;
To remove it:
delete myObject["myVar"]
as you can see in duplicate answers
var rad_id = document.getElementById('<%=radio_btn_lst.ClientID %>');
var radio = rad_id.getElementsByTagName("input");
radio[0].checked = true;
//this for javascript in asp.net try this in .aspx page
// if you select other radiobutton increase [0] to [1] or [2] like this
Interactive Interpreter Tab Completion
try:
import readline
except ImportError:
print "Unable to load readline module."
else:
import rlcompleter
readline.parse_and_bind("tab: complete")
>>> class myclass:
... def function(self):
... print "my function"
...
>>> class_instance = myclass()
>>> class_instance.<TAB>
class_instance.__class__ class_instance.__module__
class_instance.__doc__ class_instance.function
>>> class_instance.f<TAB>unction()
You will also have to set a PYTHONSTARTUP environment variable.
<button onclick="history.go(-1);">Back </button>
In GNU find
you can use -printf
parameter for that, e.g.:
find /dir1 -type f -printf "%f\n"
echo off & cls
set NUM=0 1 2 3 4 5 6 7 8 9 A B C D E F
for %%y in (%NUM%) do (
for %%x in (%NUM%) do (
color %%y%%x & for /l %%A in (1,1,200) do (dir /s)
timeout 1 >nul
)
)
pause
To decompile APK Use APKTool.
You can learn how APKTool works on http://www.decompileandroid.com/ or by reading the documentation.
I would just do a table.
<div class="elastic">
<div class="elastic_col valign-bottom">
bottom-aligned content.
</div>
</div>
And the CSS:
.elastic {
display: table;
}
.elastic_col {
display: table-cell;
}
.valign-bottom {
vertical-align: bottom;
}
See it in action:
http://jsfiddle.net/mLphM/1/
Why don't you style it out:
<canvas id="canvas" width="800" height="600" style="background: url('./images/image.jpg')">
Your browser does not support the canvas element.
</canvas>
[ ].has(obj)
assuming .indexOf()
is implemented
Object.defineProperty( Array.prototype,'has',
{
value:function(o, flag){
if (flag === undefined) {
return this.indexOf(o) !== -1;
} else { // only for raw js object
for(var v in this) {
if( JSON.stringify(this[v]) === JSON.stringify(o)) return true;
}
return false;
},
// writable:false,
// enumerable:false
})
!!! do not make Array.prototype.has=function(){...
because you'll add an enumerable element in every array and js is broken.
//use like
[22 ,'a', {prop:'x'}].has(12) // false
["a","b"].has("a") // true
[1,{a:1}].has({a:1},1) // true
[1,{a:1}].has({a:1}) // false
the use of 2nd arg (flag) forces comparation by value instead of reference
comparing raw objects
[o1].has(o2,true) // true if every level value is same
The ParallelRegression package provides a setList( ) ordered set class that is more method-complete than the options based on the ActiveState recipe. It supports all methods available for lists and most if not all methods available for sets.
The alert()
dialog is not rendered in HTML, and thus the HTML you have embedded is meaningless.
You'd need to use a custom modal to achieve that.
I would strongly suspect this is not possible, because it would be an incredible security problem if it were. For example, I could make a page which looked like a bank login page, and make the URL in the address bar look just like the real bank!
Perhaps if you explain why you want to do this, folks might be able to suggest alternative approaches...
[Edit in 2011: Since I wrote this answer in 2008, more info has come to light regarding an HTML5 technique that allows the URL to be modified as long as it is from the same origin]
Hiding on the Client Side with javascript
Using plain old javascript, you can easily hide the same element in this manner:
var myDivElem = document.getElementById("myDiv");
myDivElem.style.display = "none";
Then to show again:
myDivElem.style.display = "";
jQuery makes hiding elements a little simpler if you prefer to use jQuery:
var myDiv = $("#<%=myDiv.ClientID%>");
myDiv.hide();
... and to show:
myDiv.show();
You can find an introduction to file dialogs in the Java Tutorials. Java2s also has some example code.
Create a sub-class User with an id field and screen_name field, like this:
public class User
{
public string id { get; set; }
public string screen_name { get; set; }
}
public class Response {
public string id { get; set; }
public string text { get; set; }
public string url { get; set; }
public string width { get; set; }
public string height { get; set; }
public string size { get; set; }
public string type { get; set; }
public string timestamp { get; set; }
public User user { get; set; }
}
arr.sort(function(a,b) {
a = a.toLowerCase();
b = b.toLowerCase();
if( a == b) return 0;
if( a > b) return 1;
return -1;
});
In above function, if we just compare when lower case two value a and b, we will not have the pretty result.
Example, if array is [A, a, B, b, c, C, D, d, e, E] and we use the above function, we have exactly that array. It's not changed anything.
To have the result is [A, a, B, b, C, c, D, d, E, e], we should compare again when two lower case value is equal:
function caseInsensitiveComparator(valueA, valueB) {
var valueALowerCase = valueA.toLowerCase();
var valueBLowerCase = valueB.toLowerCase();
if (valueALowerCase < valueBLowerCase) {
return -1;
} else if (valueALowerCase > valueBLowerCase) {
return 1;
} else { //valueALowerCase === valueBLowerCase
if (valueA < valueB) {
return -1;
} else if (valueA > valueB) {
return 1;
} else {
return 0;
}
}
}
You can also use matplotlib for this.
from matplotlib.image import imread
img = imread('abc.tiff')
print(type(img))
output:
<class 'numpy.ndarray'>
If you want to add an attribute, and not an element, you have to say so:
XElement root = new XElement("Snippet");
root.Add(new XAttribute("name", "name goes here"));
root.Add(new XElement("SnippetCode", "SnippetCode"));
The code above produces the following XML element:
<Snippet name="name goes here">
<SnippetCode>SnippetCode</SnippetCode>
</Snippet>
simple difference between for and foreach
for loop is working with values.it must have condition then increment and intialization also.you have to knowledge about 'how many times loop repeated'.
foreach is working with objects and enumaretors. no need to knowledge how many times loop repeated.
A solution that worked for me is using the hidden input field in the template
<input type="hidden" id="myVar" name="variable" value="{{ variable }}">
Then getting the value in javascript this way,
var myVar = document.getElementById("myVar").value;
Just did the test and it works with toEqual
please find my test:
describe('toEqual', function() {
it('passes if arrays are equal', function() {
var arr = [1, 2, 3];
expect(arr).toEqual([1, 2, 3]);
});
});
Just for information:
toBe() versus toEqual(): toEqual() checks equivalence. toBe(), on the other hand, makes sure that they're the exact same object.
And for all of us who use Eclipse keymaps the shortcut is Ctrl+H. Expect limited options compared to eclipse or you will be disappointed.
URL-encoded payload must be provided on the body
parameter of the http.NewRequest(method, urlStr string, body io.Reader)
method, as a type that implements io.Reader
interface.
Based on the sample code:
package main
import (
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
)
func main() {
apiUrl := "https://api.com"
resource := "/user/"
data := url.Values{}
data.Set("name", "foo")
data.Set("surname", "bar")
u, _ := url.ParseRequestURI(apiUrl)
u.Path = resource
urlStr := u.String() // "https://api.com/user/"
client := &http.Client{}
r, _ := http.NewRequest(http.MethodPost, urlStr, strings.NewReader(data.Encode())) // URL-encoded payload
r.Header.Add("Authorization", "auth_token=\"XXXXXXX\"")
r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
r.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))
resp, _ := client.Do(r)
fmt.Println(resp.Status)
}
resp.Status
is 200 OK
this way.
You can change your second condition to check only the span element:
...and contains(div/span, 'someText')]
If the span isn't always inside another div you can also use
...and contains(.//span, 'someText')]
This searches for the span anywhere inside the div.
List it under technologies or something. I'd just leave it off if I were you as it's pretty much expected that you know HTML and XML at this point.
FWIW, on Ubuntu 10.04.2 LTS installing the ca-certificates-java and the ca-certificates packages fixed this problem for me.
thanks for the help, I've solved my problem :) Here is the code if anyone else needs it :D
import java.util.*;
public class HelloWorld {
public static void main(String[] Args) {
Map<Integer,List<Integer>> map = new HashMap<Integer,List<Integer>>();
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(9);
list.add(11);
map.put(1,list);
int First = list.get(1);
int Second = list.get(2);
if (First < Second) {
System.out.println("One or more of your items have been restocked. The current stock is: " + First);
Random rn = new Random();
int answer = rn.nextInt(99) + 1;
System.out.println("You are buying " + answer + " New stock");
First = First + answer;
list.set(1, First);
System.out.println("There are now " + First + " in stock");
}
}
}
When the normType
is NORM_MINMAX
, cv::normalize
normalizes _src
in such a way that the min value of dst
is alpha
and max value of dst
is beta
. cv::normalize
does its magic using only scales and shifts (i.e. adding constants and multiplying by constants).
CV_8UC1
says how many channels dst
has.
The documentation here is pretty clear: http://docs.opencv.org/modules/core/doc/operations_on_arrays.html#normalize
Not sure if you have resolved it (and if I understand correctly), but here's my idea:
If parent receives myProp, and you want it to pass to child and watch it in child, then parent has to have copy of myProp (not reference).
Try this:
new Vue({
el: '#app',
data: {
text: 'Hello'
},
components: {
'parent': {
props: ['myProp'],
computed: {
myInnerProp() { return myProp.clone(); } //eg. myProp.slice() for array
}
},
'child': {
props: ['myProp'],
watch: {
myProp(val, oldval) { now val will differ from oldval }
}
}
}
}
and in html:
<child :my-prop="myInnerProp"></child>
actually you have to be very careful when working on complex collections in such situations (passing down few times)
#alertlist li:hover:after,#alertlist li.selected:after
{
position:absolute;
top: 0;
right:-10px;
bottom:0;
border-top: 10px solid transparent;
border-bottom: 10px solid transparent;
border-left: 10px solid #303030;
content: "";
}?
The syntax for creating a new table is
CREATE TABLE new_table
AS
SELECT *
FROM old_table
This will create a new table named new_table
with whatever columns are in old_table
and copy the data over. It will not replicate the constraints on the table, it won't replicate the storage attributes, and it won't replicate any triggers defined on the table.
SELECT INTO
is used in PL/SQL when you want to fetch data from a table into a local variable in your PL/SQL block.
Syntax is Shown below:
"your condition"? "step if true":"step if condition fails"
Refer: http://www.wellho.net/mouth/754_tar-jar-war-ear-sar-files.html
tar (tape archives) - Format used is file written in serial units of fileName, fileSize, fileData - no compression. can be huge
Jar (java archive) - compression techniques used - generally contains java information like class/java files. But can contain any files and directory structure
war (web application archives) - similar like jar files only have specific directory structure as per JSP/Servlet spec for deployment purposes
ear (enterprise archives) - similar like jar files. have directory structure following J2EE requirements so that it can be deployed on J2EE application servers. - can contain multiple JAR and WAR files
While you should certainly provide more information, if you are trying to go through each row, you can just iterate with a for loop:
import numpy
m = numpy.ones((3,5),dtype='int')
for row in m:
print str(row)
In C++11, you can do this as a one-liner with a call to regex_replace
:
#include <string>
#include <regex>
using std::string;
string do_replace( string const & in, string const & from, string const & to )
{
return std::regex_replace( in, std::regex(from), to );
}
string test = "Remove all spaces";
std::cout << do_replace(test, " ", "") << std::endl;
output:
Removeallspaces
.phtml
was the standard file extension for PHP 2 programs. .php3
took over for PHP 3. When PHP 4 came out they switched to a straight .php
.
The older file extensions are still sometimes used, but aren't so common.
If you authenticate your clients with Oauth2 I think you will need underscore for at least two of your parameter names:
I have used camelCase in my (not yet published) REST API. While writing the API documentation I have been thinking of changing everything to snake_case so I don't have to explain why the Oauth params are snake_case while other params are not.
FWIW, most current browsers support the X-Frame-Options: deny directive, which works even when script is disabled.
IE8:
http://blogs.msdn.com/ie/archive/2009/01/27/ie8-security-part-vii-clickjacking-defenses.aspx
Firefox (3.6.9)
https://bugzilla.mozilla.org/show_bug.cgi?id=475530
https://developer.mozilla.org/en/The_X-FRAME-OPTIONS_response_header
Chrome/Webkit
http://blog.chromium.org/2010/01/security-in-depth-new-security-features.html
http://trac.webkit.org/changeset/42333
If you are using the Office 365 SMTP gateway then "SMTP Error: data not accepted." is the response you will get if the mailbox is full (even if you are just sending from it).
Try deleting some messages out of the mailbox.
You are calling nextElement twice. Refactor like this:
while(e.hasMoreElements()){
String param = (String) e.nextElement();
System.out.println(param);
}
I know it's malapropos, but IMHO easy way is:
def insert (source_str, insert_str, pos):
return source_str[:pos]+insert_str+source_str[pos:]
It does not need its own controller. You can use
@Html.Partial("../ControllerName/_Testimonials.cshtml")
This allows you to render the partial from any page. Just make sure the relative path is correct.
I just had the same problem. It is not a network permission but rather thread issue. Below code helped me to solve it. Put is in main activity
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9)
{
StrictMode.ThreadPolicy policy = new
StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
To change working directory in GitMSYS's Git Bash you can just use cd
cd /path/do/directory
Note that:
/
) instead of backslash.C:\stuff
" should be represented with "/c/stuff
".\
)Also, you can right click in Windows Explorer on a directory and "Git Bash here".
In jQuery just use:
$('#tblOne > tbody > tr').each(function() {...code...});
Using the children selector (>
) you will walk over all the children (and not all descendents), example with three rows:
$('table > tbody > tr').each(function(index, tr) {
console.log(index);
console.log(tr);
});
Result:
0
<tr>
1
<tr>
2
<tr>
In VanillaJS you can use document.querySelectorAll()
and walk over the rows using forEach()
[].forEach.call(document.querySelectorAll('#tblOne > tbody > tr'), function(index, tr) {
/* console.log(index); */
/* console.log(tr); */
});
To answer your specific questions:
Q1:
"Am I correct that python dicts suffer from linear access times with such inputs?"
A1: If you mean that average lookup time is O(N) where N is the number of entries in the dict, then it is highly likely that you are wrong. If you are correct, the Python community would very much like to know under what circumstances you are correct, so that the problem can be mitigated or at least warned about. Neither "sample" code nor "simplified" code are useful. Please show actual code and data that reproduce the problem. The code should be instrumented with things like number of dict items and number of dict accesses for each P where P is the number of points in the key (2 <= P <= 5)
Q2:
"As far as I know, sets have guaranteed logarithmic access times. How can I simulate dicts using sets(or something similar) in Python?"
A2: Sets have guaranteed logarithmic access times in what context? There is no such guarantee for Python implementations. Recent CPython versions in fact use a cut-down dict implementation (keys only, no values), so the expectation is average O(1) behaviour. How can you simulate dicts with sets or something similar in any language? Short answer: with extreme difficulty, if you want any functionality beyond dict.has_key(key)
.
The best thing is probably to create a variable that holds your binaries:
binaries=code1 code2
Then use that in the all
-target, to avoid repeating:
all: clean $(binaries)
Now, you can use this with the clean
-target, too, and just add some globs to catch object files and stuff:
.PHONY: clean
clean:
rm -f $(binaries) *.o
Note use of the .PHONY
to make clean
a pseudo-target. This is a GNU make feature, so if you need to be portable to other make implementations, don't use it.
I just discovered PixieDebugger. Even thought I have not yet had the time to test it, it really seems the most similar way to debug the way we're used in ipython with ipdb
It also has an "evaluate" tab
You can use request-ip, to retrieve a user's ip address. It handles quite a few of the different edge cases, some of which are mentioned in the other answers.
Disclosure: I created this module
Install:
npm install request-ip
In your app:
var requestIp = require('request-ip');
// inside middleware handler
var ipMiddleware = function(req, res, next) {
var clientIp = requestIp.getClientIp(req); // on localhost > 127.0.0.1
next();
};
Hope this helps
You'll want to use JavaScript's built-in window.location
object.
Have you tried Bananascript? It produces highly compressed and completely unreadable code.
Check /etc/phpmyadmin/config-db.php file
You have 3 options: Chrome (via Developer Tools -> Network tab), Wireshark, and Fiddler (via Log tab), however they all very basic. If you have very high volume of traffic or each frame is very large, it becomes very difficult to use them for debugging.
You can however use Fiddler with FiddlerScript to inspect WebSocket traffic in the same way you inpect HTTP traffic. Few advantages of this solution are that you can leverage many other functionalities in Fiddler, such as multiple inspectors (HexView, JSON, SyntaxView), compare packets, and find packets, etc.
Please refer to my recently written article on CodeProject, which show you how to Debug/Inspect WebSocket traffic with Fiddler (with FiddlerScript). http://www.codeproject.com/Articles/718660/Debug-Inspect-WebSocket-traffic-with-Fiddler