To convert any JSON to array, use the below code:
const usersJson: any[] = Array.of(res.json());
SELECT d.DEPTNO
, d.dname
, COUNT(e.ename) AS count
FROM emp e
INNER JOIN dept d ON e.DEPTNO = d.deptno
GROUP BY d.deptno
, d.dname;
You might consider referencing the actual date/time in the source column for Quote_Month
, then you could transform your OR
into a couple of AND
s, something like (assuing the date's in something I've chosen to call Quote_Date
)
=SUMIFS(Quote_Value,"<=90",Quote_Date,">="&DATE(2013,11,1),Quote_Date,"<="&DATE(2013,12,31),Salesman,"=JBloggs",Days_To_Close)
(I moved the interesting conditions to the front).
This approach works here because that "OR" condition is actually specifying a date range - it might not work in other cases.
Best aproach for me was:
private void grid_receptie_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
int X = 1;
foreach(DataGridViewRow row in grid_receptie.Rows)
{
row.Cells["NR_CRT"].Value = X;
X++;
}
}
I successfully solved my problem. Here is my code:
The complex JSON object:
{
"medications":[{
"aceInhibitors":[{
"name":"lisinopril",
"strength":"10 mg Tab",
"dose":"1 tab",
"route":"PO",
"sig":"daily",
"pillCount":"#90",
"refills":"Refill 3"
}],
"antianginal":[{
"name":"nitroglycerin",
"strength":"0.4 mg Sublingual Tab",
"dose":"1 tab",
"route":"SL",
"sig":"q15min PRN",
"pillCount":"#30",
"refills":"Refill 1"
}],
"anticoagulants":[{
"name":"warfarin sodium",
"strength":"3 mg Tab",
"dose":"1 tab",
"route":"PO",
"sig":"daily",
"pillCount":"#90",
"refills":"Refill 3"
}],
"betaBlocker":[{
"name":"metoprolol tartrate",
"strength":"25 mg Tab",
"dose":"1 tab",
"route":"PO",
"sig":"daily",
"pillCount":"#90",
"refills":"Refill 3"
}],
"diuretic":[{
"name":"furosemide",
"strength":"40 mg Tab",
"dose":"1 tab",
"route":"PO",
"sig":"daily",
"pillCount":"#90",
"refills":"Refill 3"
}],
"mineral":[{
"name":"potassium chloride ER",
"strength":"10 mEq Tab",
"dose":"1 tab",
"route":"PO",
"sig":"daily",
"pillCount":"#90",
"refills":"Refill 3"
}]
}
],
"labs":[{
"name":"Arterial Blood Gas",
"time":"Today",
"location":"Main Hospital Lab"
},
{
"name":"BMP",
"time":"Today",
"location":"Primary Care Clinic"
},
{
"name":"BNP",
"time":"3 Weeks",
"location":"Primary Care Clinic"
},
{
"name":"BUN",
"time":"1 Year",
"location":"Primary Care Clinic"
},
{
"name":"Cardiac Enzymes",
"time":"Today",
"location":"Primary Care Clinic"
},
{
"name":"CBC",
"time":"1 Year",
"location":"Primary Care Clinic"
},
{
"name":"Creatinine",
"time":"1 Year",
"location":"Main Hospital Lab"
},
{
"name":"Electrolyte Panel",
"time":"1 Year",
"location":"Primary Care Clinic"
},
{
"name":"Glucose",
"time":"1 Year",
"location":"Main Hospital Lab"
},
{
"name":"PT/INR",
"time":"3 Weeks",
"location":"Primary Care Clinic"
},
{
"name":"PTT",
"time":"3 Weeks",
"location":"Coumadin Clinic"
},
{
"name":"TSH",
"time":"1 Year",
"location":"Primary Care Clinic"
}
],
"imaging":[{
"name":"Chest X-Ray",
"time":"Today",
"location":"Main Hospital Radiology"
},
{
"name":"Chest X-Ray",
"time":"Today",
"location":"Main Hospital Radiology"
},
{
"name":"Chest X-Ray",
"time":"Today",
"location":"Main Hospital Radiology"
}
]
}
The jQuery code to grab the data and display it on my webpage:
$(document).ready(function() {
var items = [];
$.getJSON('labOrders.json', function(json) {
$.each(json.medications, function(index, orders) {
$.each(this, function() {
$.each(this, function() {
items.push('<div class="row">'+this.name+"\t"+this.strength+"\t"+this.dose+"\t"+this.route+"\t"+this.sig+"\t"+this.pillCount+"\t"+this.refills+'</div>'+"\n");
});
});
});
$('<div>', {
"class":'loaded',
html:items.join('')
}).appendTo("body");
});
});
create table Table1
(
id varchar(2),
name varchar(2),
PRIMARY KEY (id)
)
Create table Table1_Addr
(
addid varchar(2),
Address varchar(2),
PRIMARY KEY (addid)
)
Create table Table1_sal
(
salid varchar(2),`enter code here`
addid varchar(2),
id varchar(2),
PRIMARY KEY (salid),
index(addid),
index(id),
FOREIGN KEY (addid) REFERENCES Table1_Addr(addid),
FOREIGN KEY (id) REFERENCES Table1(id)
)
Shorter code with ES6
objArray.sort((a, b) => a.DepartmentName.toLowerCase().localeCompare(b.DepartmentName.toLowerCase()))
Need to find difference in year, if leap year the a year is of 366 days.
I dont work in oracle much, please make this better. Here is how I did:
SELECT CASE
WHEN ( (fromisleapyear = 'Y') AND (frommonth < 3))
OR ( (toisleapyear = 'Y') AND (tomonth > 2)) THEN
datedif / 366
ELSE
datedif / 365
END
yeardifference
FROM (SELECT datedif,
frommonth,
tomonth,
CASE
WHEN ( (MOD (fromyear, 4) = 0)
AND (MOD (fromyear, 100) <> 0)
OR (MOD (fromyear, 400) = 0)) THEN
'Y'
END
fromisleapyear,
CASE
WHEN ( (MOD (toyear, 4) = 0) AND (MOD (toyear, 100) <> 0)
OR (MOD (toyear, 400) = 0)) THEN
'Y'
END
toisleapyear
FROM (SELECT (:todate - :fromdate) AS datedif,
TO_CHAR (:fromdate, 'YYYY') AS fromyear,
TO_CHAR (:fromdate, 'MM') AS frommonth,
TO_CHAR (:todate, 'YYYY') AS toyear,
TO_CHAR (:todate, 'MM') AS tomonth
FROM DUAL))
Another alternative would be JasperReports: JasperReports Library. It uses iText itself and is more than a PDF library you asked for, but if it fits your needs I'd go for it.
Simply put, it allows you to design reports that can be filled during runtime. If you use a custom datasource, you might be able to integrate JasperReports easily into the existing system. It would save you the whole layouting troubles, e.g. when invoices span over more sites where each side should have a footer and so on.
My preferred solution (if all strings are numeric only):
// Order by numerical order: (Assertion: all things are numeric strings only)
foreach (var thing in things.OrderBy(int.Parse))
{
Console.Writeline(thing);
}
var student = [];
var obj = {
'first_name': name,
'last_name': name,
'age': age,
}
student.push(obj);
if(isnull({uspRptMonthlyGasRevenueByGas;1.YearTotal})) = true then
"nd"
else
totext({uspRptMonthlyGasRevenueByGas;1.YearTotal},'###.00')
The above logic should be what you are looking for.
use the exchange using java. setText = "...", for class java there are many more methods for implementation.
//button fechar
btnclose.setEnabled(false);
btnclose.setText("FECHADO");
View.OnClickListener close = new View.OnClickListener() {
@Override
public void onClick(View view) {
if (btnclose.isClickable()) {
btnOpen.setEnabled(true);
btnOpen.setText("ABRIR");
btnclose.setEnabled(false);
btnclose.setText("FECHADO");
} else {
btnOpen.setEnabled(false);
btnOpen.setText("ABERTO");
btnclose.setEnabled(true);
btnclose.setText("FECHAR");
}
Toast.makeText(getActivity(), "FECHADO", Toast.LENGTH_SHORT).show();
}
};
btnclose.setOnClickListener(close);
I got the answer.
Here is the code:
SELECT * FROM table
WHERE STR_TO_DATE(column, '%d/%m/%Y')
BETWEEN STR_TO_DATE('29/01/15', '%d/%m/%Y')
AND STR_TO_DATE('07/10/15', '%d/%m/%Y')
See this related thread. Basically, os.environ
is found on import, and os.getenv
is a wrapper to os.environ.get
, at least in CPython.
EDIT: To respond to a comment, in CPython, os.getenv
is basically a shortcut to os.environ.get
; since os.environ
is loaded at import of os
, and only then, the same holds for
os.getenv
.
Debug and Release are just labels for different solution configurations. You can add others if you want. A project I once worked on had one called "Debug Internal" which was used to turn on the in-house editing features of the application. You can see this if you go to Configuration Manager...
(it's on the Build
menu). You can find more information on MSDN Library under Configuration Manager Dialog Box.
Each solution configuration then consists of a bunch of project configurations. Again, these are just labels, this time for a collection of settings for your project. For example, our C++ library projects have project configurations called "Debug", "Debug_Unicode", "Debug_MT", etc.
The available settings depend on what type of project you're building. For a .NET project, it's a fairly small set: #define
s and a few other things. For a C++ project, you get a much bigger variety of things to tweak.
In general, though, you'll use "Debug" when you want your project to be built with the optimiser turned off, and when you want full debugging/symbol information included in your build (in the .PDB file, usually). You'll use "Release" when you want the optimiser turned on, and when you don't want full debugging information included.
I also had to deal with this problem, so here my solution. It works great for me.
1. Create class DelegateCommand
public class DelegateCommand<T> : ICommand
{
private Predicate<T> _canExecuteMethod;
private readonly Action<T> _executeMethod;
public event EventHandler CanExecuteChanged;
public DelegateCommand(Action<T> executeMethod) : this(executeMethod, null)
{
}
public DelegateCommand(Action<T> executeMethod, Predicate<T> canExecuteMethod)
{
this._canExecuteMethod = canExecuteMethod;
this._executeMethod = executeMethod ?? throw new ArgumentNullException(nameof(executeMethod), "Command is not specified.");
}
public void RaiseCanExecuteChanged()
{
if (this.CanExecuteChanged != null)
CanExecuteChanged(this, null);
}
public bool CanExecute(object parameter)
{
return _canExecuteMethod == null || _canExecuteMethod((T)parameter) == true;
}
public void Execute(object parameter)
{
_executeMethod((T)parameter);
}
}
2. Define your command
public DelegateCommand<Window> CloseWindowCommand { get; private set; }
public MyViewModel()//ctor of your viewmodel
{
//do something
CloseWindowCommand = new DelegateCommand<Window>(CloseWindow);
}
public void CloseWindow(Window win) // this method is also in your viewmodel
{
//do something
win?.Close();
}
3. Bind your command in the view
public MyView(Window win) //ctor of your view, window as parameter
{
InitializeComponent();
MyButton.CommandParameter = win;
MyButton.Command = ((MyViewModel)this.DataContext).CloseWindowCommand;
}
4. And now the window
Window win = new Window()
{
Title = "My Window",
Height = 800,
Width = 800,
WindowStartupLocation = WindowStartupLocation.CenterScreen,
};
win.Content = new MyView(win);
win.ShowDialog();
so thats it, you can also bind the command in the xaml file and find the window with FindAncestor and bind it to the command parameter.
//Date
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
let dateString = "Current date is: \(dateFormatter.string(from: Date() as Date))"
labelfordate.text = String(dateString)
//Time
let timeFormatter = DateFormatter()
timeFormatter.timeStyle = .medium
let timeString = "Current time is: \(timeFormatter.string(from: Date() as Date))"
labelfortime.text = String(timeString)
override func viewDidLoad() {
super.viewDidLoad()
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(DateAndTime.action), userInfo: nil, repeats: true)
}
func action()
{
//Date
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
let dateString = "Current date is: \(dateFormatter.string(from: Date() as Date))"
labelfordate.text = String(dateString)
//Time
let timeFormatter = DateFormatter()
timeFormatter.timeStyle = .medium
let timeString = "Current time is: \(timeFormatter.string(from: Date() as Date))"
labelfortime.text = String(timeString)
}
Note: DateAndTime in the Timer code is the Class name.
var obj = {
key1: 'value1',
key2: 'value2',
key3: 'value3',
key4: 'value4'
};
var keys = [];
for (var k in obj) keys.push(k);
console.log("total " + keys.length + " keys: " + keys);
_x000D_
What I did is first check what are the running processes by
SELECT * FROM pg_stat_activity WHERE state = 'active';
Find the process you want to kill, then type:
SELECT pg_cancel_backend(<pid of the process>)
This basically "starts" a request to terminate gracefully, which may be satisfied after some time, though the query comes back immediately.
If the process cannot be killed, try:
SELECT pg_terminate_backend(<pid of the process>)
I am facing some issue with menu change when fragment changes in ViewPager. I ended up implemented below code.
DashboardFragment
public class DashboardFragment extends BaseFragment {
private Context mContext;
private TabLayout mTabLayout;
private ViewPager mViewPager;
private DashboardPagerAdapter mAdapter;
private OnModuleChangeListener onModuleChangeListener;
private NavDashBoardActivity activityInstance;
public void setOnModuleChangeListener(OnModuleChangeListener onModuleChangeListener) {
this.onModuleChangeListener = onModuleChangeListener;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.dashboard_fragment, container, false);
}
//pass -1 if you want to get it via pager
public Fragment getFragmentFromViewpager(int position) {
if (position == -1)
position = mViewPager.getCurrentItem();
return ((Fragment) (mAdapter.instantiateItem(mViewPager, position)));
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mContext = getActivity();
activityInstance = (NavDashBoardActivity) getActivity();
mTabLayout = (TabLayout) view.findViewById(R.id.tab_layout);
mViewPager = (ViewPager) view.findViewById(R.id.view_pager);
final List<EnumUtils.Module> moduleToShow = getModuleToShowList();
mViewPager.setOffscreenPageLimit(moduleToShow.size());
for(EnumUtils.Module module :moduleToShow)
mTabLayout.addTab(mTabLayout.newTab().setText(EnumUtils.Module.getTabText(module)));
updateTabPagerAndMenu(0 , moduleToShow);
mAdapter = new DashboardPagerAdapter(getFragmentManager(),moduleToShow);
mViewPager.setOffscreenPageLimit(mAdapter.getCount());
mViewPager.setAdapter(mAdapter);
mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(final TabLayout.Tab tab) {
mViewPager.post(new Runnable() {
@Override
public void run() {
mViewPager.setCurrentItem(tab.getPosition());
}
});
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//added to redraw menu on scroll
}
@Override
public void onPageSelected(int position) {
updateTabPagerAndMenu(position , moduleToShow);
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
}
//also validate other checks and this method should be in SharedPrefs...
public static List<EnumUtils.Module> getModuleToShowList(){
List<EnumUtils.Module> moduleToShow = new ArrayList<>();
moduleToShow.add(EnumUtils.Module.HOME);
moduleToShow.add(EnumUtils.Module.ABOUT);
return moduleToShow;
}
public void setCurrentTab(final int position){
if(mViewPager != null){
mViewPager.postDelayed(new Runnable() {
@Override
public void run() {
mViewPager.setCurrentItem(position);
}
},100);
}
}
private Fragment getCurrentFragment(){
return mAdapter.getCurrentFragment();
}
private void updateTabPagerAndMenu(int position , List<EnumUtils.Module> moduleToShow){
//it helps to change menu on scroll
//http://stackoverflow.com/a/27984263/3496570
//No effect after changing below statement
ActivityCompat.invalidateOptionsMenu(getActivity());
if(mTabLayout != null)
mTabLayout.getTabAt(position).select();
if(onModuleChangeListener != null){
if(activityInstance != null){
activityInstance.updateStatusBarColor(
EnumUtils.Module.getStatusBarColor(moduleToShow.get(position)));
}
onModuleChangeListener.onModuleChanged(moduleToShow.get(position));
mTabLayout.setSelectedTabIndicatorColor(EnumUtils.Module.getModuleColor(moduleToShow.get(position)));
mTabLayout.setTabTextColors(ContextCompat.getColor(mContext,android.R.color.black)
, EnumUtils.Module.getModuleColor(moduleToShow.get(position)));
}
}
}
dashboardfragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<!-- our tablayout to display tabs -->
<android.support.design.widget.TabLayout
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:tabBackground="@android:color/white"
app:tabGravity="fill"
app:tabIndicatorHeight="4dp"
app:tabMode="scrollable"
app:tabSelectedTextColor="@android:color/black"
app:tabTextColor="@android:color/black" />
<!-- View pager to swipe views -->
<android.support.v4.view.ViewPager
android:id="@+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</LinearLayout>
DashboardPagerAdapter
public class DashboardPagerAdapter extends FragmentPagerAdapter {
private List<EnumUtils.Module> moduleList;
private Fragment mCurrentFragment = null;
public DashboardPagerAdapter(FragmentManager fm, List<EnumUtils.Module> moduleList){
super(fm);
this.moduleList = moduleList;
}
@Override
public Fragment getItem(int position) {
return EnumUtils.Module.getDashboardFragment(moduleList.get(position));
}
@Override
public int getCount() {
return moduleList.size();
}
@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
if (getCurrentFragment() != object) {
mCurrentFragment = ((Fragment) object);
}
super.setPrimaryItem(container, position, object);
}
public Fragment getCurrentFragment() {
return mCurrentFragment;
}
public int getModulePosition(EnumUtils.Module moduleName){
for(int x = 0 ; x < moduleList.size() ; x++){
if(moduleList.get(x).equals(moduleName))
return x;
}
return -1;
}
}
And in each page of Fragment setHasOptionMenu(true)
in onCreate and implement onCreateOptionMenu
. then it will work properly.
dASHaCTIVITY
public class NavDashBoardActivity extends BaseActivity
implements NavigationView.OnNavigationItemSelectedListener {
private Context mContext;
private DashboardFragment dashboardFragment;
private Toolbar mToolbar;
private DrawerLayout drawer;
private ActionBarDrawerToggle toggle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nav_dash_board);
mContext = NavDashBoardActivity.this;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
getWindow().setStatusBarColor(ContextCompat.getColor(mContext,R.color.yellow_action_bar));
}
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
updateToolbarText(new ToolbarTextBO("NCompass " ,""));
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(
this, drawer, mToolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
//onclick of back button on Navigation it will popUp fragment...
toggle.setToolbarNavigationClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(!toggle.isDrawerIndicatorEnabled()) {
getSupportFragmentManager().popBackStack();
}
}
});
final NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setItemIconTintList(null);//It helps to show icon on Navigation
updateNavigationMenuItem(navigationView);
navigationView.setNavigationItemSelectedListener(this);
//Left Drawer Upper Section
View headerLayout = navigationView.getHeaderView(0); // 0-index header
TextView userNameTv = (TextView) headerLayout.findViewById(R.id.tv_user_name);
userNameTv.setText(AuthSharePref.readUserLoggedIn().getFullName());
RoundedImageView ivUserPic = (RoundedImageView) headerLayout.findViewById(R.id.iv_user_pic);
ivUserPic.setImageResource(R.drawable.profile_img);
headerLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//close drawer and add a fragment to it
drawer.closeDrawers();//also try other methods..
}
});
//ZA code starts...
dashboardFragment = new DashboardFragment();
dashboardFragment.setOnModuleChangeListener(new OnModuleChangeListener() {
@Override
public void onModuleChanged(EnumUtils.Module module) {
if(mToolbar != null){
mToolbar.setBackgroundColor(EnumUtils.Module.getModuleColor(module));
if(EnumUtils.Module.getMenuID(module) != -1)
navigationView.getMenu().findItem(EnumUtils.Module.getMenuID(module)).setChecked(true);
}
}
});
addBaseFragment(dashboardFragment);
backStackListener();
}
public void updateStatusBarColor(int colorResourceID){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
getWindow().setStatusBarColor(colorResourceID);
}
}
private void updateNavigationMenuItem(NavigationView navigationView){
List<EnumUtils.Module> modules = DashboardFragment.getModuleToShowList();
if(!modules.contains(EnumUtils.Module.MyStores)){
navigationView.getMenu().findItem(R.id.nav_my_store).setVisible(false);
}
if(!modules.contains(EnumUtils.Module.Livewall)){
navigationView.getMenu().findItem(R.id.nav_live_wall).setVisible(false);
}
}
private void backStackListener(){
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
if(getSupportFragmentManager().getBackStackEntryCount() >= 1)
{
toggle.setDrawerIndicatorEnabled(false); //disable "hamburger to arrow" drawable
toggle.setHomeAsUpIndicator(R.drawable.ic_arrow_back_black_24dp); //set your own
///toggle.setDrawerArrowDrawable();
///toggle.setDrawerIndicatorEnabled(false); // this will hide hamburger image
///Toast.makeText(mContext,"Update to Arrow",Toast.LENGTH_SHORT).show();
}
else{
toggle.setDrawerIndicatorEnabled(true);
}
if(getSupportFragmentManager().getBackStackEntryCount() >0){
if(getCurrentFragment() instanceof DashboardFragment){
Fragment subFragment = ((DashboardFragment) getCurrentFragment())
.getViewpager(-1);
}
}
else{
}
}
});
}
private void updateToolBarTitle(String title){
getSupportActionBar().setTitle(title);
}
public void updateToolBarColor(String hexColor){
if(mToolbar != null)
mToolbar.setBackgroundColor(Color.parseColor(hexColor));
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (drawer.isDrawerOpen(GravityCompat.START))
getMenuInflater().inflate(R.menu.empty, menu);
return super.onCreateOptionsMenu(menu);//true is wriiten first..
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == android.R.id.home)
{
if (drawer.isDrawerOpen(GravityCompat.START))
drawer.closeDrawer(GravityCompat.START);
else {
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
} else
drawer.openDrawer(GravityCompat.START);
}
return false;///true;
}
return false;// false so that fragment can also handle the menu event. Otherwise it is handled their
///return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_my_store) {
// Handle the camera action
dashboardFragment.setCurrentTab(EnumUtils.Module.MyStores);
}
}else if (id == R.id.nav_log_out) {
Dialogs.logOut(mContext);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void updateToolbarText(ToolbarTextBO toolbarTextBO){
mToolbar.setTitle("");
mToolbar.setSubtitle("");
if(toolbarTextBO.getTitle() != null && !toolbarTextBO.getTitle().isEmpty())
mToolbar.setTitle(toolbarTextBO.getTitle());
if(toolbarTextBO.getDescription() != null && !toolbarTextBO.getDescription().isEmpty())
mToolbar.setSubtitle(toolbarTextBO.getDescription());*/
}
@Override
public void onPostCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
super.onPostCreate(savedInstanceState, persistentState);
// Sync the toggle state after onRestoreInstanceState has occurred.
toggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
toggle.onConfigurationChanged(newConfig);
}
}
You can use multiple way based on sitaution:
If you Variable is limited to specific Number or String, best way is using ngSwitch or ngIf:
<!-- foo = 3 -->
<div [ngSwitch]="foo">
<div *ngSwitchCase="1">First Number</div>
<div *ngSwitchCase="2">Second Number</div>
<div *ngSwitchCase="3">Third Number</div>
<div *ngSwitchDefault>Other Number</div>
</div>
<!-- foo = 3 -->
<ng-template [ngIf]="foo === 1">First Number</ng-template>
<ng-template [ngIf]="foo === 2">Second Number</ng-template>
<ng-template [ngIf]="foo === 3">Third Number</ng-template>
<!-- foo = 'David' -->
<div [ngSwitch]="foo">
<div *ngSwitchCase="'Daniel'">Daniel String</div>
<div *ngSwitchCase="'David'">David String</div>
<div *ngSwitchCase="'Alex'">Alex String</div>
<div *ngSwitchDefault>Other String</div>
</div>
<!-- foo = 'David' -->
<ng-template [ngIf]="foo === 'Alex'">Alex String</ng-template>
<ng-template [ngIf]="foo === 'David'">David String</ng-template>
<ng-template [ngIf]="foo === 'Daniel'">Daniel String</ng-template>
Above not suitable for if elseif else codes and dynamic codes, you can use below code:
<!-- foo = 5 -->
<ng-container *ngIf="foo >= 1 && foo <= 3; then t13"></ng-container>
<ng-container *ngIf="foo >= 4 && foo <= 6; then t46"></ng-container>
<ng-container *ngIf="foo >= 7; then t7"></ng-container>
<!-- If Statement -->
<ng-template #t13>
Template for foo between 1 and 3
</ng-template>
<!-- If Else Statement -->
<ng-template #t46>
Template for foo between 4 and 6
</ng-template>
<!-- Else Statement -->
<ng-template #t7>
Template for foo greater than 7
</ng-template>
Note: You can choose any format, but notice every code has own problems
Go to this link
Download version tar.gz for windows and just extract files to the folder by your needs. On the left pane, you can select which version of openjdk to download
Tutorial: unzip as expected. You need to set system variable PATH to include your directory with openjdk so you can type java -version in console.
Just completing the Vijay's post...
Manifest
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
Function
public static boolean createDirIfNotExists(String path) {
boolean ret = true;
File file = new File(Environment.getExternalStorageDirectory(), path);
if (!file.exists()) {
if (!file.mkdirs()) {
Log.e("TravellerLog :: ", "Problem creating Image folder");
ret = false;
}
}
return ret;
}
Usage
createDirIfNotExists("mydir/"); //Create a directory sdcard/mydir
createDirIfNotExists("mydir/myfile") //Create a directory and a file in sdcard/mydir/myfile.txt
You could check for errors
if(createDirIfNotExists("mydir/")){
//Directory Created Success
}
else{
//Error
}
date.setTime(milliseconds);
this is for set milliseconds in date
long milli = date.getTime();
This is for get time in milliseconds.
Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT
The whole concept of inversion of control means you are free from a chore to instantiate objects manually and provide all necessary dependencies.
When you annotate class with appropriate annotation (e.g. @Service
) Spring will automatically instantiate object for you. If you are not familiar with annotations you can also use XML file instead. However, it's not a bad idea to instantiate classes manually (with the new
keyword) in unit tests when you don't want to load the whole spring context.
setSize()
or setBounds()
can be used when no layout manager is being used.
However, if you are using a layout manager you can provide hints to the layout manager using the setXXXSize()
methods like setPreferredSize()
and setMinimumSize()
etc.
And be sure that the component's container uses a layout manager that respects the requested size. The FlowLayout
, GridBagLayout
, and SpringLayout
managers use the component's preferred size (the latter two depending on the constraints you set), but BorderLayout
and GridLayout
usually don't.If you specify new size hints for a component that's already visible, you need to invoke the revalidate method on it to make sure that its containment hierarchy is laid out again. Then invoke the repaint method.
Do the following:
<html>
)This is a hacky way, but it's the easiest way to do this.
This command actually works
\curl -L https://get.rvm.io | bash -s stable --ruby
Don't know (as for now) why, but this one helped:
@media print {
html, body {
border: 1px solid white;
height: 99%;
page-break-after: avoid;
page-break-before: avoid;
}
}
Hope someone will save his hair while fighting with the problem... ;)
This is what works fine for me:
<form name="f" action="/search">
<input name="q" onfocus="fff=1" />
</form>
fff will be a global variable which name is absolutely irrelevant and which aim will be to stop the generic onload event to force focus in that input.
<body onload="if(!this.fff)document.f.q.focus();">
<!-- ... the rest of the page ... -->
</body>
From: http://webreflection.blogspot.com.br/2009/06/inputfocus-something-really-annoying.html
I faced the same issue in my scenario as follow:
I created textbook table first with
create table textbook(txtbk_isbn varchar2(13)
primary key,txtbk_title varchar2(40),
txtbk_author varchar2(40) );
Then chapter table:
create table chapter(txtbk_isbn varchar2(13),chapter_title varchar2(40),
constraint pk_chapter primary key(txtbk_isbn,chapter_title),
constraint chapter_txtbook foreign key (txtbk_isbn) references textbook (txtbk_isbn));
Then topic table:
create table topic(topic_id varchar2(20) primary key,topic_name varchar2(40));
Now when I wanted to create a relationship called chapter_topic between chapter (having composite primary key) and topic (having single column primary key), I faced issue with following query:
create table chapter_topic(txtbk_isbn varchar2(13),chapter_title varchar2(40),topic_id varchar2(20),
primary key (txtbk_isbn, chapter_title, topic_id),
foreign key (txtbk_isbn) references textbook(txtbk_isbn),
foreign key (chapter_title) references chapter(chapter_title),
foreign key (topic_id) references topic (topic_id));
The solution was to refer to composite foreign key as below:
create table chapter_topic(txtbk_isbn varchar2(13),chapter_title varchar2(40),topic_id varchar2(20),
primary key (txtbk_isbn, chapter_title, topic_id),
foreign key (txtbk_isbn, chapter_title) references chapter(txtbk_isbn, chapter_title),
foreign key (topic_id) references topic (topic_id));
Thanks to APC post in which he mentioned in his post a statement that:
Common reasons for this are
- the parent lacks a constraint altogether
- the parent table's constraint is a compound key and we haven't referenced all the columns in the foreign key statement.
- the referenced PK constraint exists but is DISABLED
While there might be a way I would tend to keep that kind of logic out of the Model. I agree that you shouldn't put that in the view (keep it skinny) but unless the model is returning a url as a piece of data to the controller, the routing stuff should be in the controller.
in my experince the problem using result()
and result_array()
in my JSON
if using result()
there no problem its works but if using result_array()
i got error "Trying to get property of non-object"
so im not search into deep the problem so i just using result()
if using JSON
and using result_array()
if not using JSON
I had the same error when trying to change the first view controller that was loaded in
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
At first I didn't really know where the error was coming from precisely so I narrowed it down and found out what went wrong. It turns out that I was trying to change the display of a view before it actually came on screen. The solution was hence to move this code in the viewcontroller that was giving me trouble from
- (void)viewDidLoad
to
- (void)viewDidAppear:(BOOL)animated
and the error stopped appearing. My problem specifically was caused by making a UIAlertView
show.
In your case I suggest you check out the code in the tabBarController's active view controller (as it is probably a problem in that view controller). If that doesn't work, try to set the starting settings in the nib file instead of in code - or if you want to do it in code, try moving the code to the tabBarController's active viewcontroller's appropriate method.
Good luck!
There are plenty of answers here explaining what you could do (I use the different field name one) but the simple (and as-yet unstated) answer to your question is 'no' - you can't have a different text and value using just HTML.
Hi try async:false in your ajax call..
As others have said, std::max_element()
and std::min_element()
return iterators, which need to be dereferenced to obtain the value.
The advantage of returning an iterator (rather than just the value) is that it allows you to determine the position of the (first) element in the container with the maximum (or minimum) value.
For example (using C++11 for brevity):
#include <vector>
#include <algorithm>
#include <iostream>
int main()
{
std::vector<double> v {1.0, 2.0, 3.0, 4.0, 5.0, 1.0, 2.0, 3.0, 4.0, 5.0};
auto biggest = std::max_element(std::begin(v), std::end(v));
std::cout << "Max element is " << *biggest
<< " at position " << std::distance(std::begin(v), biggest) << std::endl;
auto smallest = std::min_element(std::begin(v), std::end(v));
std::cout << "min element is " << *smallest
<< " at position " << std::distance(std::begin(v), smallest) << std::endl;
}
This yields:
Max element is 5 at position 4
min element is 1 at position 0
Using std::minmax_element()
as suggested in the comments above may be faster for large data sets, but may give slightly different results. The values for my example above would be the same, but the position of the "max" element would be 9
since...
If several elements are equivalent to the largest element, the iterator to the last such element is returned.
Use json_decode
to convert the JSON string to a PHP array, then use normal PHP array functions on it.
$json = '[{"var1":"9","var2":"16","var3":"16"},{"var1":"8","var2":"15","var3":"15"}]';
$data = json_decode($json);
var_dump($data[0]['var1']); // outputs '9'
Names = []
for line in open('names.txt','r').readlines():
Names.append(line.strip())
strip() cut spaces in before and after string...
You can have a look at this page showing Deep Folder Copy, it uses recursive means to iterate throught the files and has some really nice tips, like filtering techniques etc.
http://www.codeproject.com/Tips/512208/Folder-Directory-Deep-Copy-including-sub-directori
Try this:
{[0-9]{1,3}:[0-9]{1,3}}
The {1,3}
means "match between 1 and 3 of the preceding characters".
Cast them to a Number
$('#total_price').val(Number(a)+Number(b));
But before you do that
if (!isNaN($('input[name=service_price]').val()) {...
If there is not substantial history on one end (aka if it is just a single readme commit on the github end), I often find it easier to manually copy the readme to my local repo and do a git push -f
to make my version the new root commit.
I find it is slightly less complicated, doesn't require remembering an obscure flag, and keeps the history a bit cleaner.
CAST(
FLOOR(
CAST( GETDATE() AS FLOAT )
)
AS DATETIME
)
http://www.bennadel.com/blog/122-Getting-Only-the-Date-Part-of-a-Date-Time-Stamp-in-SQL-Server.htm
Create the below function
Alter FUNCTION InitialCap(@String VARCHAR(8000))
RETURNS VARCHAR(8000)
AS
BEGIN
DECLARE @Position INT;
SELECT @String = STUFF(LOWER(@String),1,1,UPPER(LEFT(@String,1))) COLLATE Latin1_General_Bin,
@Position = PATINDEX('%[^A-Za-z''][a-z]%',@String COLLATE Latin1_General_Bin);
WHILE @Position > 0
SELECT @String = STUFF(@String,@Position,2,UPPER(SUBSTRING(@String,@Position,2))) COLLATE Latin1_General_Bin,
@Position = PATINDEX('%[^A-Za-z''][a-z]%',@String COLLATE Latin1_General_Bin);
RETURN @String;
END ;
Then call it like
select dbo.InitialCap(columnname) from yourtable
You can take using the following method
mysqldump -d <database name> > <filename.sql> // -d : without data
Hope it will helps you
Switch to text-mode
M-x text-mode
Highlight block to indent
Indent
C+M \
Switch back to whatever mode..
Please try CURRENT_TIME()
or now()
functions
"INSERT INTO contactinfo (name, email, subject, date, comments)
VALUES ('$name', '$email', '$subject', NOW(), '$comments')"
OR
"INSERT INTO contactinfo (name, email, subject, date, comments)
VALUES ('$name', '$email', '$subject', CURRENT_TIME(), '$comments')"
OR you could try with PHP date
function here:
$date = date("Y-m-d H:i:s");
if you already know your folder is: E:\ftproot\sales then you do not need to use Server.MapPath, this last one is needed if you only have a relative virtual path like ~/folder/folder1 and you want to know the real path in the disk...
I experienced this issue today and started searching on internet. In my case there was no table in my DB. I forgot to import the tables on the online server. I did it and all works fine.
@Patrick I would improve your solution a bit
@Override
public Object deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
ObjectNode objectNode = jp.readValueAsTree();
JsonNode wrapped = objectNode.get(wrapperKey);
JsonParser parser = node.traverse();
parser.setCodec(jp.getCodec());
Vendor mapped = parser.readValueAs(Vendor.class);
return mapped;
}
It works faster :)
It looks like there has been an update to React that doesn't allow you to set the "paths"
in the tsconfig.json
anylonger.
Nicely React just outputs a warning:
The following changes are being made to your tsconfig.json file:
- compilerOptions.paths must not be set (aliased imports are not supported)
then updates your tsconfig.json
and removes the entire "paths"
section for you. There is a way to get around this run
npm run eject
This will eject all of the create-react-scripts
settings by adding config
and scripts
directories and build/config files into your project. This also allows a lot more control over how everything is built, named etc. by updating the {project}/config/*
files.
Then update your tsconfig.json
{
"compilerOptions": {
"baseUrl": "./src",
{…}
"paths": {
"assets/*": [ "assets/*" ],
"styles/*": [ "styles/*" ]
}
},
}
You can use std::reverse
like this
std::reverse(str.begin(), str.end());
Keep in mind that as of PHP 5.5.0 the mysql_connect()
function is deprecated, and it is completely removed in PHP 7
More info can be found on the php documentation:
Quote:
Warning
This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:
* mysqli_connect()
* PDO::__construct()
As said Will Wagner, in old version of jsp you should always use c:out
to output dynamic text.
Moreover, using this syntax:
<c:out value="${person.name}">No name</c:out>
you can display the text "No name" when name is null.
All the above answers directly answer the question. But here's a less direct solution but a potentially more important idea, to provoke thought.
Since line lengths are arbitrary, all the bytes of the file before the nth line need to be read. If you have a huge file or need to repeat this task many times, and this process is time-consuming, then you should seriously think about whether you should be storing your data in a different way in the first place.
The real solution is to have an index, e.g. at the start of the file, indicating the positions where the lines begin. You could use a database format, or just add a table at the start of the file. Alternatively create a separate index file to accompany your large text file.
e.g. you might create a list of character positions for newlines:
awk 'BEGIN{c=0;print(c)}{c+=length()+1;print(c+1)}' file.txt > file.idx
then read with tail
, which actually seek
s directly to the appropriate point in the file!
e.g. to get line 1000:
tail -c +$(awk 'NR=1000' file.idx) file.txt | head -1
You are not setting a classpath that includes your compiled class! java
can't find any classes if you don't tell it where to look.
java -cp [compiler outpur dir] HelloWorld
Incidentally you do not need to set CLASSPATH the way you have done.
To remove a scrollbar from a view (and its subclass) via xml:
android:scrollbars="none"
http://developer.android.com/reference/android/view/View.html#attr_android:scrollbars
Simply:
/^([^0-9]*)$/
That pattern matches any number of characters that is not 0
through 9
.
I recommend checking out http://regexpal.com/. It will let you easily test out a regex.
To make autoresizing of UITableViewCell to work make sure you are doing these changes :
In your UIViewController's viewDidLoad function set below UITableView Properties :
self.tableView.estimatedRowHeight = <minimum cell height>
self.tableView.rowHeight = UITableViewAutomaticDimension
Differentiate between the two cases you named:
To indicate that the requested operation is not supported and most likely never will, throw an UnsupportedOperationException
.
To indicate the requested operation has not been implemented yet, choose between this:
Use the NotImplementedException
from apache commons-lang which was available in commons-lang2 and has been re-added to commons-lang3 in version 3.2.
Implement your own NotImplementedException
.
Throw an UnsupportedOperationException
with a message like "Not implemented, yet".
A local variable is only accessible from within the block of it's initialization. Also a local variable begins with a lower case letter (a-z) or underscore (_).
And instance variable is an instance of self
and begins with a @
Also an instance variable belongs to the object itself. Instance variables are the ones that you perform methods on i.e. .send
etc
example:
@user = User.all
The @user
is the instance variable
And Uninitialized instance variables have a value of Nil
For executing something in the UI Thread after 5 seconds:
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
@Override
public void run() {
//Do something here
}
}, 5000);
This works for me...
A good summary of LLVM is this:
At the frontend you have Perl, and many other high level languages. At the backend, you have the natives code that run directly on the machine.
At the centre is your intermediate code representation. If every high level language can be represented in this LLVM IR format, then analysis tools based on this IR can be easily reused - that is the basic rationale.
Agree no matches in your example.
If you mean both columns on either then need a query like this or need to re-examine the data design.
Select TableA.Col1, TableA.Col2, TableB.Val
FROM TableA
INNER JOIN TableB
ON TableA.Col1 = TableB.Col1 OR TableA.Col2 = TableB.Col2
OR TableA.Col2 = TableB.Col1 OR TableA.Col1 = TableB.Col2
I slightly disagree with the above. The unsigned char
simply means: Use the most significant bit instead of treating it as a bit flag for +/- sign when performing arithmetic operations.
It makes significance if you use char
as a number for instance:
typedef char BYTE1;
typedef unsigned char BYTE2;
BYTE1 a;
BYTE2 b;
For variable a
, only 7 bits are available and its range is (-127 to 127) = (+/-)2^7 -1.
For variable b
all 8 bits are available and the range is 0 to 255 (2^8 -1).
If you use char
as character, "unsigned" is completely ignored by the compiler just as comments are removed from your program.
Try Vim, emacs (has a low maximum buffer size limit if compiled in 32-bit mode), hex tools
If you've got an image in the Icons folder of your project and its build action is "Resource", you can refer to it like this:
<Image Source="/Icons/play_small.png" />
That's the simplest way to do it. This is the only way I could figure doing it purely from the resource standpoint and no project files:
var resourceManager = new ResourceManager(typeof (Resources));
var bitmap = resourceManager.GetObject("Search") as System.Drawing.Bitmap;
var memoryStream = new MemoryStream();
bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Bmp);
memoryStream.Position = 0;
var bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = memoryStream;
bitmapImage.EndInit();
this.image1.Source = bitmapImage;
adding HttpClientModule
in app.module.ts
file in import
section fixed my issue.
For those who want a "standard" text formatting of the hash, you can use something like the following:
static string Hash(string input)
{
using (SHA1Managed sha1 = new SHA1Managed())
{
var hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(input));
var sb = new StringBuilder(hash.Length * 2);
foreach (byte b in hash)
{
// can be "x2" if you want lowercase
sb.Append(b.ToString("X2"));
}
return sb.ToString();
}
}
This will produce a hash like 0C2E99D0949684278C30B9369B82638E1CEAD415
.
Or for a code golfed version:
static string Hash(string input)
{
var hash = new SHA1Managed().ComputeHash(Encoding.UTF8.GetBytes(input));
return string.Concat(hash.Select(b => b.ToString("x2")));
}
Use the HLS Downloader Google Chrome extension to get the link to the M3U playlist. Its icon in the browser bar will show the number of playlists found on the current webpage. Clicking on the icon you can then see a list of the playlist link and then use the copy button next to a link to copy it.
Then use the youtube-dl program to download the file.
youtube-dl --all-subs -f mp4 -o "file-name-to-save-as.mp4" "https://link-from-Google_Chrome-HLS_Downloader_extension"
Explanation of command line options:
-f mp4 = Output format mp4
--all-subs = Download all subtitles
-o "file-name-to-save-as.mp4" = Name of the file to save the video as.
"https://link-from-Google_Chrome-HLS_Downloader_extension" = This is the link to the playlist you copied from the HLS Downloader extension.
If you use the same configuration options all the time for youtube-dl you may want to take a look at the configuration options for youtube-dl, as this can save you a lot of typing.
The HLS Downloader extension is free and open source under the MIT license if you want to see the code it can be found on its project page on Github.
Setting window full height for empty divs
1st solution with absolute positioning - FIDDLE
.div1 {
position: absolute;
top: 0;
bottom: 0;
width: 25%;
}
.div2 {
position: absolute;
top: 0;
left: 25%;
bottom: 0;
width: 75%;
}
2nd solution with static (also can be used a relative) positioning & jQuery - FIDDLE
.div1 {
float: left;
width: 25%;
}
.div2 {
float: left;
width: 75%;
}
$(function(){
$('.div1, .div2').css({ height: $(window).innerHeight() });
$(window).resize(function(){
$('.div1, .div2').css({ height: $(window).innerHeight() });
});
});
It's one of the common mistake everybody make while working with jQuery, Basically $ is an alias of jQuery() so when you try to call/access it before declaring the function will endup throwing this error.
Reasons might be
1) Path to jQuery library you included is not correct.
2) Added library after the script were you see that error
To solve this
Load the jquery library beginning of all your javascript files/scripts.
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
A sample command that exhibits the symptom: sed 's/./@/' <<<$'\xfc'
fails, because byte 0xfc
is not a valid UTF-8 char.
Note that, by contrast, GNU sed
(Linux, but also installable on macOS) simply passes the invalid byte through, without reporting an error.
Using the formerly accepted answer is an option if you don't mind losing support for your true locale (if you're on a US system and you never need to deal with foreign characters, that may be fine.)
However, the same effect can be had ad-hoc for a single command only:
LC_ALL=C sed -i "" 's|"iphoneos-cross","llvm-gcc:-O3|"iphoneos-cross","clang:-Os|g' Configure
Note: What matters is an effective LC_CTYPE
setting of C
, so LC_CTYPE=C sed ...
would normally also work, but if LC_ALL
happens to be set (to something other than C
), it will override individual LC_*
-category variables such as LC_CTYPE
. Thus, the most robust approach is to set LC_ALL
.
However, (effectively) setting LC_CTYPE
to C
treats strings as if each byte were its own character (no interpretation based on encoding rules is performed), with no regard for the - multibyte-on-demand - UTF-8 encoding that OS X employs by default, where foreign characters have multibyte encodings.
In a nutshell: setting LC_CTYPE
to C
causes the shell and utilities to only recognize basic English letters as letters (the ones in the 7-bit ASCII range), so that foreign chars. will not be treated as letters, causing, for instance, upper-/lowercase conversions to fail.
Again, this may be fine if you needn't match multibyte-encoded characters such as é
, and simply want to pass such characters through.
If this is insufficient and/or you want to understand the cause of the original error (including determining what input bytes caused the problem) and perform encoding conversions on demand, read on below.
The problem is that the input file's encoding does not match the shell's.
More specifically, the input file contains characters encoded in a way that is not valid in UTF-8 (as @Klas Lindbäck stated in a comment) - that's what the sed
error message is trying to say by invalid byte sequence
.
Most likely, your input file uses a single-byte 8-bit encoding such as ISO-8859-1
, frequently used to encode "Western European" languages.
Example:
The accented letter à
has Unicode codepoint 0xE0
(224) - the same as in ISO-8859-1
. However, due to the nature of UTF-8 encoding, this single codepoint is represented as 2 bytes - 0xC3 0xA0
, whereas trying to pass the single byte 0xE0
is invalid under UTF-8.
Here's a demonstration of the problem using the string voilà
encoded as ISO-8859-1
, with the à
represented as one byte (via an ANSI-C-quoted bash string ($'...'
) that uses \x{e0}
to create the byte):
Note that the sed
command is effectively a no-op that simply passes the input through, but we need it to provoke the error:
# -> 'illegal byte sequence': byte 0xE0 is not a valid char.
sed 's/.*/&/' <<<$'voil\x{e0}'
To simply ignore the problem, the above LCTYPE=C
approach can be used:
# No error, bytes are passed through ('á' will render as '?', though).
LC_CTYPE=C sed 's/.*/&/' <<<$'voil\x{e0}'
If you want to determine which parts of the input cause the problem, try the following:
# Convert bytes in the 8-bit range (high bit set) to hex. representation.
# -> 'voil\x{e0}'
iconv -f ASCII --byte-subst='\x{%02x}' <<<$'voil\x{e0}'
The output will show you all bytes that have the high bit set (bytes that exceed the 7-bit ASCII range) in hexadecimal form. (Note, however, that that also includes correctly encoded UTF-8 multibyte sequences - a more sophisticated approach would be needed to specifically identify invalid-in-UTF-8 bytes.)
Performing encoding conversions on demand:
Standard utility iconv
can be used to convert to (-t
) and/or from (-f
) encodings; iconv -l
lists all supported ones.
Examples:
Convert FROM ISO-8859-1
to the encoding in effect in the shell (based on LC_CTYPE
, which is UTF-8
-based by default), building on the above example:
# Converts to UTF-8; output renders correctly as 'voilà'
sed 's/.*/&/' <<<"$(iconv -f ISO-8859-1 <<<$'voil\x{e0}')"
Note that this conversion allows you to properly match foreign characters:
# Correctly matches 'à' and replaces it with 'ü': -> 'voilü'
sed 's/à/ü/' <<<"$(iconv -f ISO-8859-1 <<<$'voil\x{e0}')"
To convert the input BACK to ISO-8859-1
after processing, simply pipe the result to another iconv
command:
sed 's/à/ü/' <<<"$(iconv -f ISO-8859-1 <<<$'voil\x{e0}')" | iconv -t ISO-8859-1
Use forward slashes to specify the UNC Path:
open('//HOST/share/path/to/file')
(if your Python client code is also running under Windows)
join(',', array_map(function (array $tag) { return $tag['tag_name']; }, $array))
Bind variable can be used in Oracle SQL query with "in" clause.
Works in 10g; I don't know about other versions.
Bind variable is varchar up to 4000 characters.
Example: Bind variable containing comma-separated list of values, e.g.
:bindvar = 1,2,3,4,5
select * from mytable
where myfield in
(
SELECT regexp_substr(:bindvar,'[^,]+', 1, level) items
FROM dual
CONNECT BY regexp_substr(:bindvar, '[^,]+', 1, level) is not null
);
(Same info as I posted here: How do you specify IN clause in a dynamic query using a variable? )
In addition to other answers, I recommend you to look at this list:
14 Great Android apps that are also open source
For me, NewsBlur, Hacker News Reader and Astrid were the most helpful. Still, I don't know whether they are "suitable for basic learning".
As Drake states this could be done with FileReader. However, what I present here is a functional version. Take in consideration that the big problem with doing this with JavaScript is to reset the input file. Well, this restricts to only JPG (for other formats you will have to change the mime type and the magic number):
<form id="form-id">
<input type="file" id="input-id" accept="image/jpeg"/>
</form>
<script type="text/javascript">
$(function(){
$("#input-id").on('change', function(event) {
var file = event.target.files[0];
if(file.size>=2*1024*1024) {
alert("JPG images of maximum 2MB");
$("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
return;
}
if(!file.type.match('image/jp.*')) {
alert("only JPG images");
$("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
return;
}
var fileReader = new FileReader();
fileReader.onload = function(e) {
var int32View = new Uint8Array(e.target.result);
//verify the magic number
// for JPG is 0xFF 0xD8 0xFF 0xE0 (see https://en.wikipedia.org/wiki/List_of_file_signatures)
if(int32View.length>4 && int32View[0]==0xFF && int32View[1]==0xD8 && int32View[2]==0xFF && int32View[3]==0xE0) {
alert("ok!");
} else {
alert("only valid JPG images");
$("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
return;
}
};
fileReader.readAsArrayBuffer(file);
});
});
</script>
Take in consideration that this was tested on latest versions of Firefox and Chrome, and on IExplore 10.
Most decompilers for Java are based on JAD. It's a great tool, but unfortunately hasn't been updated for a while and does not handle Java 1.5+ classes very well. I have not seen any tools that will properly handle 1.5+ classes.
Error was due to file name of the lambda function. While creating the lambda function it will ask for Lambda function handler. You have to name it as your Python_File_Name.Method_Name. In this scenario I named it as lambda.lambda_handler (lambda.py is the file name).
Update: Nowadays installing is done with pip, but libyaml is still required to build the C extension (on mac):
brew install libyaml
python -m pip install pyyaml
Outdated method:
For MacOSX (mavericks), the following seems to work:
brew install libyaml
sudo python -m easy_install pyyaml
You mean:
Wscript.Echo "Like this?"
If you run that under wscript.exe
(the default handler for the .vbs extension, so what you'll get if you double-click the script) you'll get a "MessageBox" dialog with your text in it. If you run that under cscript.exe
you'll get output in your console window.
Check out the manual: http://www.php.net/manual/en/datetime.format.php
<?php
$date = new DateTime('2000-01-01');
echo $date->format('Y-m-d H:i:s');
?>
Will output: 2000-01-01 00:00:00
The accepted solution only works on arrays, but not objects or associative arrays. Unfortunately, since Angular depends on the JavaScript implementation of array enumeration, the order of object properties cannot be consistently controlled. Some browsers may iterate through object properties lexicographically, but this cannot be guaranteed.
e.g. Given the following assignment:
$scope.cards = {
"card2": {
values: {
opt1: 9,
opt2: 12
}
},
"card1": {
values: {
opt1: 9,
opt2: 11
}
}
};
and the directive <ul ng-repeat="(key, card) in cards | orderBy:myValueFunction">
, ng-repeat may iterate over "card1" prior to "card2", regardless of sort order.
To workaround this, we can create a custom filter to convert the object to an array, and then apply a custom sort function before returning the collection.
myApp.filter('orderByValue', function () {
// custom value function for sorting
function myValueFunction(card) {
return card.values.opt1 + card.values.opt2;
}
return function (obj) {
var array = [];
Object.keys(obj).forEach(function (key) {
// inject key into each object so we can refer to it from the template
obj[key].name = key;
array.push(obj[key]);
});
// apply a custom sorting function
array.sort(function (a, b) {
return myValueFunction(b) - myValueFunction(a);
});
return array;
};
});
We cannot iterate over (key, value) pairings in conjunction with custom filters (since the keys for arrays are numerical indexes), so the template should be updated to reference the injected key names.
<ul ng-repeat="card in cards | orderByValue">
<li>{{card.name}} {{value(card)}}</li>
</ul>
Here is a working fiddle utilizing a custom filter on an associative array: http://jsfiddle.net/av1mLpqx/1/
Reference: https://github.com/angular/angular.js/issues/1286#issuecomment-22193332
For Chrome, Safari and Firefox, just use this:
form.append("blob", blob, filename);
(see MDN documentation)
If all else fails, Ctrl-H (search and replace) with "=" in both boxes (in other words, search on = and replace it with the same =). Seems to do the trick.
Another answer I would have for this would be to take a pragmatic approach and keep your REST API contract simple. In my case I had refactored my REST API to make things more testable without resorting to JavaScript or XHR, just simple HTML forms and links.
So to be more specific on your question above, I'd just use return code 200
and have the returned message contain a JSON message that your application can understand. Depending on your needs it may require the ID of the object that is newly created so the web application can get the data in another call.
One note, in my refactored API contract, POST responses should not contain any cacheable data as POSTs are not really cachable, so limit it to IDs that can be requested and cached using a GET request.
can also Use parameterized each with index and the element.
$('#selectIntegrationConf').find('option').each(function(index,element){
console.log(index);
console.log(element.value);
console.log(element.text);
});
// this will also work
$('#selectIntegrationConf option').each(function(index,element){
console.log(index);
console.log(element.value);
console.log(element.text);
});
To generate random numbers with bash use the $RANDOM internal Bash function. Note that $RANDOM should not be used to generate an encryption key. $RANDOM is generated by using your current process ID (PID) and the current time/date as defined by the number of seconds elapsed since 1970.
echo $RANDOM % 10 + 1 | bc
Packaging of pom
is used in projects that aggregate other projects, and in projects whose only useful output is an attached artifact from some plugin. In your case, I'd guess that your top-level pom includes <modules>...</modules>
to aggregate other directories, and the actual output is the result of one of the other (probably sub-) directories. It will, if coded sensibly for this purpose, have a packaging of war
.
As a developer of SpeedView: GPS speedometer for Android, I must have tried every possible solution to this problem, all with the same negative result. Let's reiterate what doesn't work:
So here's the only working solution I found, and the one that I actually use in my app. Let's say we have this simple class that implements the GpsStatus.Listener:
private class MyGPSListener implements GpsStatus.Listener {
public void onGpsStatusChanged(int event) {
switch (event) {
case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
if (mLastLocation != null)
isGPSFix = (SystemClock.elapsedRealtime() - mLastLocationMillis) < 3000;
if (isGPSFix) { // A fix has been acquired.
// Do something.
} else { // The fix has been lost.
// Do something.
}
break;
case GpsStatus.GPS_EVENT_FIRST_FIX:
// Do something.
isGPSFix = true;
break;
}
}
}
OK, now in onLocationChanged() we add the following:
@Override
public void onLocationChanged(Location location) {
if (location == null) return;
mLastLocationMillis = SystemClock.elapsedRealtime();
// Do something.
mLastLocation = location;
}
And that's it. Basically, this is the line that does it all:
isGPSFix = (SystemClock.elapsedRealtime() - mLastLocationMillis) < 3000;
You can tweak the millis value of course, but I'd suggest to set it around 3-5 seconds.
This actually works and although I haven't looked at the source code that draws the native GPS icon, this comes close to replicating its behaviour. Hope this helps someone.
Here is what I use since I am not running > 5.2
function getCurrentOrParentDirectory($type='current')
{
if ($type == 'current') {
$path = dirname(__FILE__);
} else {
$path = dirname(dirname(__FILE__));
}
$position = strrpos($path, '/') + 1;
return substr($path, $position);
}
Double dirname with file as suggested by @mike b for the parent directory, and current directory is found by just using that syntax once.
Note this function only returns the NAME, slashes have to be added afterwards.
=LEFT(A1,FIND(IF(
ISERROR(
FIND("_",A1)
),A1,RIGHT(A1,
LEN(A1)-FIND("~",
SUBSTITUTE(A1,"_","~",
LEN(A1)-LEN(SUBSTITUTE(A1,"_",""))
)
)
)
),A1,1)-2)
Normally you'd just stick the code in Page_Load
in your .aspx
page's code-behind.
if (someVar) {
Item1.Visible = true;
Item2.Visible = false;
} else {
Item1.Visible = false;
Item2.Visible = true;
}
This assumes you've got Item1
and Item2
laid out on the page already.
if youd dont have adb in folder android-sdk-macosx/platform-tools/
you should install platform tools first. Run android-sdk-macosx/tools/android
and Install platform tools from Android SDK manager.
#/bin/bash
# $1 is the file name
# usage: this_script <filename>
IP_address="xx.xxx.xx.xx"
username="username"
domain=my.ftp.domain
password=password
echo "
verbose
open $IP_address
USER $username $password
put $1
bye
" | ftp -n > ftp_$$.log
In linux, this worked for me:
adb logcat | grep `adb shell ps | grep your.package | awk '{print $2}'`
If you have PHP >= 5.1:
function isWeekend($date) {
return (date('N', strtotime($date)) >= 6);
}
otherwise:
function isWeekend($date) {
$weekDay = date('w', strtotime($date));
return ($weekDay == 0 || $weekDay == 6);
}
Just change the port number used e.g. 8000 then call the http://localhost:8080
change to
fscanf(myFile, "%1d", &numberArray[i]);
$("#select_id").find("option:selected").text();
It is helpful if your control is on Server side. In .NET it looks like:
$('#<%= dropdownID.ClientID %>').find("option:selected").text();
If you can't know the progress you should not fake it by abusing a progress bar, instead just display some sort of busy icon like en.wikipedia.org/wiki/Throbber#Spinning_wheel Show it when starting the task and hide it when it's finished. That would make for a more "honest" GUI.
With typescript we can leverage type aliases, like so:
type KeyboardEvent = {
target: HTMLInputElement,
key: string,
};
const onKeyPress = (e: KeyboardEvent) => {
if ('Enter' === e.key) { // Enter keyboard was pressed!
submit(e.target.value);
e.target.value = '';
return;
}
// continue handle onKeyPress input events...
};
For the very limited case of constant, 8-bit input, this method costs no memory or CPU at run-time:
#define MSB2LSB(b) (((b)&1?128:0)|((b)&2?64:0)|((b)&4?32:0)|((b)&8?16:0)|((b)&16?8:0)|((b)&32?4:0)|((b)&64?2:0)|((b)&128?1:0))
I used this for ARINC-429 where the bit order (endianness) of the label is opposite the rest of the word. The label is often a constant, and conventionally in octal.
Here's how I used it to define a constant, because the spec defines this label as big-endian 205 octal.
#define LABEL_HF_COMM MSB2LSB(0205)
More examples:
assert(0b00000000 == MSB2LSB(0b00000000));
assert(0b10000000 == MSB2LSB(0b00000001));
assert(0b11000000 == MSB2LSB(0b00000011));
assert(0b11100000 == MSB2LSB(0b00000111));
assert(0b11110000 == MSB2LSB(0b00001111));
assert(0b11111000 == MSB2LSB(0b00011111));
assert(0b11111100 == MSB2LSB(0b00111111));
assert(0b11111110 == MSB2LSB(0b01111111));
assert(0b11111111 == MSB2LSB(0b11111111));
assert(0b10101010 == MSB2LSB(0b01010101));
You can not do that...
via css the URL
you put on the background-image
is just for the image.
Via HTML
you have to add the href
for your hyperlink in this way:
<a href="http://home.com" id="logo">Your logo</a>
With text-indent
and some other css
you can adjust your a element to show just the image and clicking on it you will go to your link.
EDIT:
I'm here again to show you and explain why my solution is much better:
<a href="http://home.com" id="logo">Your logo name</a>
This block of HTML
is SEO friendly because you have some text inside your link!
How to style it with css:
#logo {
background-image: url(images/logo.png);
display: block;
margin: 0 auto;
text-indent: -9999px;
width: 981px;
height: 180px;
}
Then if you don't care about SEO good to choose the other answer.
I tried everything, but the problem persisted. After that I did this and it worked ASAP (As Smooth As Possible).
new String(byteArray, Charset.defaultCharset())
This will convert a byte array to the default charset in java. It may throw exceptions depending on what you supply with the byteArray.
Open Source: CMU Sphinx
Shareware: http://www.e-speaking.com/ (Windows)
Commercial: Dragon NaturallySpeaking (Windows)
LOL, I was doing all the steps here - I ended up doing the unpairing/repairing steps from the "given by Surjeet" answer. It didn't work, and then I noticed that when I clicked the "connect via network" button, the same yellow box would pop up that pops up when you repair, saying "busy" - I got frustrated and just started hammering the "connect via network" button, clicking it quickly for probably like 15 - 20 clicks - it started spazzing out, but eventually landed on being able to connect to the network. Before that worked, I also shut my wifi off and turned it on again, as suggested by one of these answers, but clicking the "connect via network" button really fast did the trick...LOL
Also, before I hammered the button, I linked the device support folders, although I'm not sure if it did anything:
open the terminal
cd /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport
ln -s 13.3 13.4
ls -l 13.4
restart Xcode and retry run on device
Said to do it here - https://forums.developer.apple.com/thread/126940 - I edited the folder version in my comment to adjust to the latest version of iOS 13.4.
EDIT
I believe I figured out what my problem was, I had to stop my Little Snitch
network filter. Also, after I was able to connect by hammering the button, the "connect via IP address" option appeared in the dropdown when you right click on the device in the devices manager in xcode, it wasn't there before I was able to connect ultra-hacky style the first time. If I connect, and then turn my network filter on, it disconnects my phone.
If you are running windows try this:
to start it when you wand to use it, follow the same steps and click start this time
Seems like you expected the query to return running totals, but it must have given you the same values for both partitions of AccountID
.
To obtain running totals with SUM() OVER ()
, you need to add an ORDER BY
sub-clause after PARTITION BY …
, like this:
SUM(Quantity) OVER (PARTITION BY AccountID ORDER BY ID)
But remember, not all database systems support ORDER BY
in the OVER
clause of a window aggregate function. (For instance, SQL Server didn't support it until the latest version, SQL Server 2012.)
I was facing the same issue but above solutions did not help.
So, after lot of struggle I found out that sestatus was set to enforce which blocks all the ports and by setting it to permissive all the issues were resolved.
sudo setenforce 0
Hope this helps someone like me.
@AamirAdnan's answer missing field.label
; the other way to show the errors in few lines.
{% if form.errors %}
<!-- Error messaging -->
<div id="errors">
<div class="inner">
<p>There were some errors in the information you entered. Please correct the following:</p>
<ul>
{% for field in form %}
{% if field.errors %}<li>{{ field.label }}: {{ field.errors|striptags }}</li>{% endif %}
{% endfor %}
</ul>
</div>
</div>
<!-- /Error messaging -->
{% endif %}
ALLOW-FROM is not supported in Chrome or Safari. See MDN article: https://developer.mozilla.org/en-US/docs/Web/HTTP/X-Frame-Options
You are already doing the work to make a custom header and send it with the correct data, can you not just exclude the header when you detect it is from a valid partner and add DENY to every other request? I don't see the benefit of AllowFrom when you are already dynamically building the logic up?
city = 'Ribeir\xc3\xa3o Preto'
print city.decode('cp1252').encode('utf-8')
It's actually do-able without JavaScript, but using pure CSS + HTML with sticky position. Just add "position:sticky" to the cells you'd like to freeze.
For building a table, you can either use or CSS grid, and this technique works on both of them.
Here is an example formatting with table tag ( live demo here ):
<table>
<tr><th class="head"></th class="head"><th></th> ... </tr>
<tr><th class="head"></th> <th></th> ... </tr>
...
</table>
<style type="text/css">
.head { position: sticky; top: 0; left: 0;}
</style>
And here is an example with CSS Grid ( live demo here ):
<div class="grid">
<!-- cells to freeze -->
<div class="entry head"></div>
<div class="entry head"></div>
...
<!-- normal cells -->
<div class="entry"></div>
...
</div>
<style type="text/css">
.grid {
display: grid;
grid-template-columns: repeat(<your-cell-count>, <cell-size>);
}
.entry.head { position: sticky; top: 0; left: 0 }
</style>
You probably will need to take care of the cells frozen both horizontally and vertically ( e.g., setting a z-index larger than others ) but it will be still CSS thing.
I think the main drawback of this approach is, probably, the browser compatibility issue. Check Can I Use CSS-sticky and Can I use CSS grid before using these techniques.
You have to allocate the buffer with mallock, and give the read write the pointer to it.
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(){
ssize_t nrd;
int fd;
int fd1;
char* buffer = malloc(100*sizeof(char));
fd = open("bli.txt", O_RDONLY);
fd1 = open("bla.txt", O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR);
while (nrd = read(fd,buffer,sizeof(buffer))) {
write(fd1,buffer,nrd);
}
close(fd);
close(fd1);
free(buffer);
return 0;
}
Make sure that the rad file exists and contains something. It's not perfect but it works.
Open a terminal, cd to the path of your Vagrantfile and write this
(Linux)
vagrant ssh -c "hostname -I | cut -d' ' -f2" 2>/dev/null
(OS X)
vagrant ssh -c "hostname -I | cut -d' ' -f2" 2>/dev/null | pbcopy
The command for Linux also works for windows. I have no way to test, sorry.
source: https://coderwall.com/p/etzdmq/get-vagrant-box-guest-ip-from-host
You can use .sortBy
, it will always return an ascending list:
_.sortBy([2, 3, 1], function(num) {
return num;
}); // [1, 2, 3]
But you can use the .reverse method to get it descending:
var array = _.sortBy([2, 3, 1], function(num) {
return num;
});
console.log(array); // [1, 2, 3]
console.log(array.reverse()); // [3, 2, 1]
Or when dealing with numbers add a negative sign to the return to descend the list:
_.sortBy([-3, -2, 2, 3, 1, 0, -1], function(num) {
return -num;
}); // [3, 2, 1, 0, -1, -2, -3]
Under the hood .sortBy
uses the built in .sort([handler])
:
// Default is ascending:
[2, 3, 1].sort(); // [1, 2, 3]
// But can be descending if you provide a sort handler:
[2, 3, 1].sort(function(a, b) {
// a = current item in array
// b = next item in array
return b - a;
});
eval(s);
Remember though, that eval is very powerful and quite unsafe. You better be confident that the script you are executing is safe and unmutable by users.
Found this works for me:
In the link:
<button type="button" class="btn btn-success" data-toggle="modal" data-target="#message<?php echo $row['id'];?>">Message</button>
In the modal:
<div id="message<?php echo $row['id'];?>" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
<?php echo $row['id'];?>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
You need to specify both source and destination, and if you want to copy directories you should look at the -r option.
So to recursively copy /home/user/whatever from remote server to your current directory:
scp -pr user@remoteserver:whatever .
If you are sure you haven't messed the jar, then please clean the project and perform mvn clean install
. This should solve the problem.
That's not how you send file on postman. What you did is sending a string which is the path of your image, nothing more.
What you should do is;
You're ready to go.
In your Django view,
from rest_framework.views import APIView
from rest_framework.parsers import MultiPartParser
from rest_framework.decorators import parser_classes
@parser_classes((MultiPartParser, ))
class UploadFileAndJson(APIView):
def post(self, request, format=None):
thumbnail = request.FILES["file"]
info = json.loads(request.data['info'])
...
return HttpResponse()
For React Native Init approach (without expo) use:
npm start -- --reset-cache
Project
will effects Columns in the table while Select
effects the Rows. on other hand Project
is use to select the columns with specefic properties rather than Select the all of columns data
This seems unnecessary, but VBA is a strange place. If you declare an array variable, then set it using Array()
then pass the variable into your function, VBA will be happy.
Sub test()
Dim fString As String
Dim arr() As Variant
arr = Array("foo", "bar")
fString = processArr(arr)
End Sub
Also your function processArr()
could be written as:
Function processArr(arr() As Variant) As String
processArr = Replace(Join(arr()), " ", "")
End Function
If you are into the whole brevity thing.
This error appear because the compiler could not found "my-upload-key.keystore" file in your project
After you have generated the file you need to paste it into project's andorid/app folder
this worked for me!
An update to @jrgns (with some slight syntax differences) solution.
$result = mysql_query('SELECT * FROM `some_table`');
if (!$result) die('Couldn\'t fetch records');
$num_fields = mysql_num_fields($result);
$headers = array();
for ($i = 0; $i < $num_fields; $i++)
{
$headers[] = mysql_field_name($result , $i);
}
$fp = fopen('php://output', 'w');
if ($fp && $result)
{
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="export.csv"');
header('Pragma: no-cache');
header('Expires: 0');
fputcsv($fp, $headers);
while ($row = mysql_fetch_row($result))
{
fputcsv($fp, array_values($row));
}
die;
}
Solution : SpreadsheetApp.getActiveSheet().getRange('F2').setValue('hello')
Explanation :
Setting value in a cell in spreadsheet to which script is attached
SpreadsheetApp.getActiveSpreadsheet().getSheetByName(SHEET_NAME).getRange(RANGE).setValue(VALUE);
Setting value in a cell in sheet which is open currently and to which script is attached
SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(RANGE).setValue(VALUE);
Setting value in a cell in some spreadsheet to which script is NOT attached (Destination sheet name known)
SpreadsheetApp.openById(SHEET_ID).getSheetByName(SHEET_NAME).getRange(RANGE).setValue(VALUE);
Setting value in a cell in some spreadsheet to which script is NOT attached (Destination sheet position known)
SpreadsheetApp.openById(SHEET_ID).getSheets()[POSITION].getRange(RANGE).setValue(VALUE);
These are constants, you must define them yourself
SHEET_ID
SHEET_NAME
POSITION
VALUE
RANGE
By script attached to a sheet I mean that script is residing in the script editor of that sheet. Not attached means not residing in the script editor of that sheet. It can be in any other place.
Here is a Swift version. Note that if you do not want to send form data it is still important to send the empty form boundary. Flask in particular expects form data followed by file data and will not populate request.files
without the first boundary.
let composedData = NSMutableData()
// Set content type header
let BoundaryConstant = "--------------------------3d74a90a3bfb8696"
let contentType = "multipart/form-data; boundary=\(BoundaryConstant)"
request.setValue(contentType, forHTTPHeaderField: "Content-Type")
// Empty form boundary
composedData.appendData("--\(BoundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
// Build multipart form to send image
composedData.appendData("--\(BoundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
composedData.appendData("Content-Disposition: form-data; name=\"file\"; filename=\"image.jpg\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
composedData.appendData("Content-Type: image/jpeg\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
composedData.appendData(rawData!)
composedData.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
composedData.appendData("--\(BoundaryConstant)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
request.HTTPBody = composedData
// Get content length
let length = "\(composedData.length)"
request.setValue(length, forHTTPHeaderField: "Content-Length")
The dot is not part of the class name. It's only used in CSS/jQuery selector notation. Try this instead:
if ($('#navigation a').hasClass('active')) {
$(this).parent().addClass('active');
}
If $(this)
refers to that anchor, you have to change it to $('#navigation a')
as well because the if condition does not have jQuery callback scope.
See query:
SELECT * FROM Table1 WHERE
id NOT IN (SELECT
e.id
FROM
Table1 e
INNER JOIN
Table2 s ON e.id = s.id);
Conceptually would be: Fetching the matching records in subquery and then in main query fetching the records which are not in subquery.
H.264 is a new standard for video compression which has more advanced compression methods than the basic MPEG-4 compression. One of the advantages of H.264 is the high compression rate. It is about 1.5 to 2 times more efficient than MPEG-4 encoding. This high compression rate makes it possible to record more information on the same hard disk.
The image quality is also better and playback is more fluent than with basic MPEG-4 compression. The most interesting feature however is the lower bit-rate required for network transmission.
So the 3 main advantages of H.264 over MPEG-4 compression are:
- Small file size for longer recording time and better network transmission.
- Fluent and better video quality for real time playback
- More efficient mobile surveillance applicationH264 is now enshrined in MPEG4 as part 10 also known as AVC
Refer to: http://www.velleman.eu/downloads/3/h264_vs_mpeg4_en.pdf
Hope this helps.
If you want to catch the Back Button have a look at this post on the Android Developer Blog. It covers the easier way to do this in Android 2.0 and the best way to do this for an application that runs on 1.x and 2.0.
However, if your Activity is Stopped it still may be killed depending on memory availability on the device. If you want a process to run with no UI you should create a Service
. The documentation says the following about Services:
A service doesn't have a visual user interface, but rather runs in the background for an indefinite period of time. For example, a service might play background music as the user attends to other matters, or it might fetch data over the network or calculate something and provide the result to activities that need it.
These seems appropriate for your requirements.
First edit the Nginx configuration file (nginx.conf
)
Location: sudo nano /etc/nginx/nginx.conf
Add following codes:
http {
client_max_body_size 100M;
}
Then Add the following lines in PHP configuration file(php.ini
)
Location: sudo gedit /etc/php5/fpm/php.ini
Add following codes:
memory_limit = 128M
post_max_size = 20M
upload_max_filesize = 10M
I see many (all) posts above relying on LBound
/UBound
calls upon yet potentially uninitialized VBA dynamic array, what causes application's inevitable death ...
Erratic code:
Dim x As Long
Dim arr1() As SomeType
...
x = UBound(arr1) 'crashes
Correct code:
Dim x As Long
Dim arr1() As SomeType
...
ReDim Preserve arr1(0 To 0)
...
x = UBound(arr1)
... i.e. any code where Dim arr1()
is followed immediatelly by LBound(arr1)
/UBound(arr1)
calls without ReDim arr1(...)
in between, crashes. The roundabout is to employ an On Error Resume Next
and check the Err.Number
right after the LBound(arr1)
/UBound(arr1)
call - it should be 0 if the array is initialized, otherwise non-zero. As there is some VBA built-in misbehavior, the further check of array's limits is needed. Detailed explanation may everybody read at Chip Pearson's website (which should be celebrated as a Mankind Treasure Of VBA Wisdom ...)
Heh, that's my first post, believe it is legible.
You can use bash arrays
$ str_array=("continuation"
"lines")
then
$ echo "${str_array[*]}"
continuation lines
there is an extra space, because (after bash manual):
If the word is double-quoted,
${name[*]}
expands to a single word with the value of each array member separated by the first character of the IFS variable
So set IFS=''
to get rid of extra space
$ IFS=''
$ echo "${str_array[*]}"
continuationlines
There's little need to set all the variables you're setting. CMake sets them to reasonable defaults. You should definitely not modify CMAKE_BINARY_DIR
or CMAKE_CACHEFILE_DIR
. Treat these as read-only.
First remove the existing problematic cache file from the src directory:
cd src
rm CMakeCache.txt
cd ..
Then remove all the set()
commands and do:
cd Compile && rm -rf *
cmake ../src
As long as you're outside of the source directory when running CMake, it will not modify the source directory unless your CMakeList explicitly tells it to do so.
Once you have this working, you can look at where CMake puts things by default, and only if you're not satisfied with the default locations (such as the default value of EXECUTABLE_OUTPUT_PATH
), modify only those you need. And try to express them relative to CMAKE_BINARY_DIR
, CMAKE_CURRENT_BINARY_DIR
, PROJECT_BINARY_DIR
etc.
If you look at CMake documentation, you'll see variables partitioned into semantic sections. Except for very special circumstances, you should treat all those listed under "Variables that Provide Information" as read-only inside CMakeLists.
There are 4 dimensions of the tensor you want to convert.
[:, ::-1, :, :]
:
means that the first dimension should be copied as it is and converted, same goes for the third and fourth dimension.
::-1
means that for the second axes it reverses the the axes
FYI Dark theme is now in the Dev Version of MySQL Workbench
Update: From what I can tell it is Natively built into MySQL Workbench 8.0.15
for MAC OS X
The package I downloaded was mysql-workbench-community-8.0.15-macos-x86_64.dmg
The reason of why your code throws an UnboundLocalError
is already well explained in other answers.
But it seems to me that you're trying to build something that works like itertools.count()
.
So why don't you try it out, and see if it suits your case:
>>> from itertools import count
>>> counter = count(0)
>>> counter
count(0)
>>> next(counter)
0
>>> counter
count(1)
>>> next(counter)
1
>>> counter
count(2)
I think this is quite overkill for a dictionary semantics, since dictionary is by definition is a collection of keys and its respective values, just like the way we see a book of language dictionary that contains a word as the key and its descriptive meaning as the value.
But you can represent a dictionary that can contain collection of values, for example:
Dictionary<String,List<Customer>>
Or a dictionary of a key and the value as a dictionary:
Dictionary<Customer,Dictionary<Order,OrderDetail>>
Then you'll have a dictionary that can have multiple values.
$('#fm_submit').submit(function(e){_x000D_
e.preventDefault();_x000D_
var ck_box = $('input[type="checkbox"]:checked').length;_x000D_
_x000D_
// return in firefox or chrome console _x000D_
// the number of checkbox checked_x000D_
console.log(ck_box); _x000D_
_x000D_
if(ck_box > 0){_x000D_
alert(ck_box);_x000D_
} _x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form name = "frmTest[]" id="fm_submit">_x000D_
<input type="checkbox" value="true" checked="true" >_x000D_
<input type="checkbox" value="true" checked="true" >_x000D_
<input type="checkbox" >_x000D_
<input type="checkbox" >_x000D_
<input type="submit" id="fm_submit" name="fm_submit" value="Submit">_x000D_
</form>_x000D_
<div class="container"></div>
_x000D_
Observable and subject both are observable's means an observer can track them. but both of them have some unique characteristics. Further there are total 3 type of subjects each of them again have unique characteristics. lets try to to understand each of them.
you can find the practical example here on stackblitz. (You need to check the console to see the actual output)
Observables
They are cold: Code gets executed when they have at least a single observer.
Creates copy of data: Observable creates copy of data for each observer.
Uni-directional: Observer can not assign value to observable(origin/master).
Subject
They are hot: code gets executed and value gets broadcast even if there is no observer.
Shares data: Same data get shared between all observers.
bi-directional: Observer can assign value to observable(origin/master).
If are using using subject then you miss all the values that are broadcast before creation of observer. So here comes Replay Subject
ReplaySubject
They are hot: code gets executed and value get broadcast even if there is no observer.
Shares data: Same data get shared between all observers.
bi-directional: Observer can assign value to observable(origin/master). plus
Replay the message stream: No matter when you subscribe the replay subject you will receive all the broadcasted messages.
In subject and replay subject you can not set the initial value to observable. So here comes Behavioral Subject
BehaviorSubject
They are hot: code gets executed and value get broadcast even if there is no observer.
Shares data: Same data get shared between all observers.
bi-directional: Observer can assign value to observable(origin/master). plus
Replay the message stream: No matter when you subscribe the replay subject you will receive all the broadcasted messages.
You can set initial value: You can initialize the observable with default value.
You can also Preview your report so it's automatically compiled.
Assign the onclick like this:
divTag.onclick = printWorking;
The onclick property will not take a string when assigned. Instead, it takes a function reference (in this case, printWorking
).
The onclick attribute can be a string when assigned in HTML, e.g. <div onclick="func()"></div>
, but this is generally not recommended.
You'd most likely need to extract code from a secure web page (https protocol). In the following example, the html file is being saved into c:\temp\filename.html Enjoy!
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
/**
* <b>Get the Html source from the secure url </b>
*/
public class HttpsClientUtil {
public static void main(String[] args) throws Exception {
String httpsURL = "https://stackoverflow.com";
String FILENAME = "c:\\temp\\filename.html";
BufferedWriter bw = new BufferedWriter(new FileWriter(FILENAME));
URL myurl = new URL(httpsURL);
HttpsURLConnection con = (HttpsURLConnection) myurl.openConnection();
con.setRequestProperty ( "User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0" );
InputStream ins = con.getInputStream();
InputStreamReader isr = new InputStreamReader(ins, "Windows-1252");
BufferedReader in = new BufferedReader(isr);
String inputLine;
// Write each line into the file
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
bw.write(inputLine);
}
in.close();
bw.close();
}
}
Your code looks great, the only thing i see is that you did not include the collapsed class in your button selector. http://www.bootply.com/cpHugxg2f8 Note: Requires JavaScript plugin If JavaScript is disabled and the viewport is narrow enough that the navbar collapses, it will be impossible to expand the navbar and view the content within the .navbar-collapse.
The responsive navbar requires the collapse plugin to be included in your version of Bootstrap.
<div class="navbar-wrapper">
<div class="container">
<nav class="navbar navbar-inverse navbar-static-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Project name</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li><a href="">Page 1</a>
</li>
<li><a href="">Page 2</a>
</li>
<li><a href="">Page 3</a>
</li>
</ul>
</div>
</div>
</nav>
</div>
</div>
Reuses cells while scrolling up/down - this is possible with implementing View Holder in the listView adapter, but it was an optional thing, while in the RecycleView it's the default way of writing adapter.
Decouples list from its container - so you can put list items easily at run time in the different containers (linearLayout, gridLayout) with setting LayoutManager.
Example:
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
//or
mRecyclerView.setLayoutManager(new GridLayoutManager(this, 2));
mRecyclerView.setLayoutManager(new GridLayoutManager(this, 3));
Animates common list actions.
Animations are decoupled and delegated to ItemAnimator
.
There is more about RecyclerView, but I think these points are the main ones.
LayoutManager
i) LinearLayoutManager - which supports both vertical and horizontal lists,
ii) StaggeredLayoutManager - which supports Pinterest like staggered lists,
iii) GridLayoutManager - which supports displaying grids as seen in Gallery apps.
And the best thing is that we can do all these dynamically as we want.
FYI, from November 2018 anyone who wants access Twitter’s APIs must apply for a Twitter Development Account by visiting https://developer.twitter.com/. Once your application has been approved then only you'll be able to create Twitter apps.
Once the Twitter Developer Account is ready:
1) Go to https://developer.twitter.com/.
2) Click on Apps and then click on Create an app.
3) Provide an App Name & Description.
4) Enter a website name in the Website URL field.
5) Click on Create.
6) Navigate to your app, then click on Details and then go to Keys and Tokens.
Reference: http://www.technocratsid.com/getting-twitter-consumer-api-access-token-keys/
// Change the way body-parser is used
const bodyParser = require('body-parser');
var rawBodySaver = function (req, res, buf, encoding) {
if (buf && buf.length) {
req.rawBody = buf.toString(encoding || 'utf8');
}
}
app.use(bodyParser.json({ verify: rawBodySaver, extended: true }));
// Now we can access raw-body any where in out application as follows
request.rawBody;
Use the Refresh method:
context.Refresh(RefreshMode.StoreWins, yourEntity);
or in alternative dispose your current context and create a new one.
In my case, I was careless while merging the application.yml file, and I've unnecessary indented my properties to the right.
I've indented it like this:
spring:
application:
name: applicationName
............................
myProperties:
property1: property1value
While the code expected it to be like this:
spring:
application:
name: applicationName
.............................
myProperties:
property1: property1value
There is an easy way of doing it in Node.js
var object1 = {name: "John"};
var object2 = {location: "San Jose"};
To combine/extend this we can use ...
operator in ECMA6
var object1 = {name: "John"};_x000D_
var object2 = {location: "San Jose"};_x000D_
_x000D_
var result = {_x000D_
...object1,_x000D_
...object2_x000D_
}_x000D_
_x000D_
console.log(result)
_x000D_
While the security is the same, it may be easier for fraudulent applications to dupe users using an iframe since they have more flexibility regarding where the frame is placed.
The question says "How to declare array of zeros ..." but then the sample code references the Python list:
buckets = [] # this is a list
However, if someone is actually wanting to initialize an array, I suggest:
from array import array
my_arr = array('I', [0] * count)
The Python purist might claim this is not pythonic and suggest:
my_arr = array('I', (0 for i in range(count)))
The pythonic version is very slow and when you have a few hundred arrays to be initialized with thousands of values, the difference is quite noticeable.
unset($array[$index]);
You could create an image thumbnail, and link it to the actual pdf as an inline popup using something like http://orangoo.com/labs/GreyBox/
If you use a BlockingCollection to schedule the task, the producer can run the potentially long running task and the consumer can use the TryTake method which has timeout and cancellation token built in.
In codeigniter there is no need to sennd "data" in ajax post method.. here is the example .
searchThis = 'This text will be search';
$.ajax({
type: "POST",
url: "<?php echo site_url();?>/software/search/"+searchThis,
dataType: "html",
success:function(data){
alert(data);
},
});
Note : in url , software is the controller name , search is the function name and searchThis is the variable that i m sending.
Here is the controller.
public function search(){
$search = $this->uri->segment(3);
echo '<p>'.$search.'</p>';
}
I hope you can get idea for your work .
Too late to answer, but an iterative approach sounds easy here:
1) for a set of n
elements, get the value of 2^n
. There will be 2^n no.of subsets. (2^n because each element can be either present(1) or absent(0). So for n elements there will be 2^n subsets. ). Eg:
for 3 elements, say {a,b,c}, there will be 2^3=8 subsets
2) Get a binary representation of 2^n
. Eg:
8 in binary is 1000
3) Go from 0
to (2^n - 1)
. In each iteration, for each 1 in the binary representation, form a subset with elements that correspond to the index of that 1 in the binary representation.
Eg:
For the elements {a, b, c}
000 will give {}
001 will give {c}
010 will give {b}
011 will give {b, c}
100 will give {a}
101 will give {a, c}
110 will give {a, b}
111 will give {a, b, c}
4) Do a union of all the subsets thus found in step 3. Return. Eg:
Simple union of above sets!
Try:
which( !is.na(p), arr.ind=TRUE)
Which I think is just as informative and probably more useful than the output you specified, But if you really wanted the list version, then this could be used:
> apply(p, 1, function(x) which(!is.na(x)) )
[[1]]
[1] 2 3
[[2]]
[1] 4 7
[[3]]
integer(0)
[[4]]
[1] 5
[[5]]
integer(0)
Or even with smushing together with paste:
lapply(apply(p, 1, function(x) which(!is.na(x)) ) , paste, collapse=", ")
The output from which
function the suggested method delivers the row and column of non-zero (TRUE) locations of logical tests:
> which( !is.na(p), arr.ind=TRUE)
row col
[1,] 1 2
[2,] 1 3
[3,] 2 4
[4,] 4 5
[5,] 2 7
Without the arr.ind
parameter set to non-default TRUE, you only get the "vector location" determined using the column major ordering the R has as its convention. R-matrices are just "folded vectors".
> which( !is.na(p) )
[1] 6 11 17 24 32
Here is another way to do it that IMHO is more simple and elegant than any of the other answers provided.
This program has a function that takes two parameters, prints them out and also prints the sum:
import multiprocessing
def main():
with multiprocessing.Pool(10) as pool:
params = [ (2, 2), (3, 3), (4, 4) ]
pool.starmap(printSum, params)
# end with
# end function
def printSum(num1, num2):
mySum = num1 + num2
print('num1 = ' + str(num1) + ', num2 = ' + str(num2) + ', sum = ' + str(mySum))
# end function
if __name__ == '__main__':
main()
output is:
num1 = 2, num2 = 2, sum = 4
num1 = 3, num2 = 3, sum = 6
num1 = 4, num2 = 4, sum = 8
See the python docs for more info:
https://docs.python.org/3/library/multiprocessing.html#module-multiprocessing.pool
In particular be sure to check out the starmap
function.
I'm using Python 3.6, I'm not sure if this will work with older Python versions
Why there is not a very straight-forward example like this in the docs, I'm not sure.
How about
l1 = [2,3,1,4,5]
l2 = [l1.index(x) for x in sorted(l1)]
Never give borderRadius to your <Text />
always wrap that <Text />
inside your <View />
or in your <TouchableOpacity/>
.
borderRadius on <Text />
will work perfectly on Android devices. But on IOS devices it won't work.
So keep this in your practice to wrap your <Text/>
inside your <View/>
or on <TouchableOpacity/>
and then give the borderRadius to that <View />
or <TouchableOpacity />
so that it will work on both Android as well as on IOS devices.
For example:-
<TouchableOpacity style={{borderRadius: 15}}>
<Text>Button Text</Text>
</TouchableOpacity>
-Thanks
MessageBox.Show(
"your message",
"window title",
MessageBoxButtons.OK,
MessageBoxIcon.Asterisk //For Info Asterisk
MessageBoxIcon.Exclamation //For triangle Warning
)
Use a dot or a pipe as the field separator:
awk -v FS='[.|]' '{
printf "%s%s %s.%s\n", toupper(substr($4,1,1)), substr($4,2), $1, $2
}' << END
[email protected]|com.emailclient.account
[email protected]|com.socialsite.auth.account
END
gives:
Emailclient [email protected]
Socialsite [email protected]
You can set max connections using:
set global max_connections = '1 < your number > 100000';
This will set your number of mysql connection unti (Requires SUPER
privileges).
Other answers already on Stackoverflow:
From perlfaq8:
When you build modules, tell Perl where to install the modules.
For Makefile.PL-based distributions, use the INSTALL_BASE option when generating Makefiles:
perl Makefile.PL INSTALL_BASE=/mydir/perl
You can set this in your CPAN.pm configuration so modules automatically install in your private library directory when you use the CPAN.pm shell:
% cpan
cpan> o conf makepl_arg INSTALL_BASE=/mydir/perl
cpan> o conf commit
For Build.PL-based distributions, use the --install_base option:
perl Build.PL --install_base /mydir/perl
You can configure CPAN.pm to automatically use this option too:
% cpan
cpan> o conf mbuildpl_arg '--install_base /mydir/perl'
cpan> o conf commit
Note that starting Python 3.8
, and the introduction of assignment expressions (PEP 572) (:=
operator), it's possible to improve a bit on Krzysztof Krason's solution by capturing the match result directly within the if condition as a variable and re-use it in the condition's body:
# pattern = '<title>(.*)</title>'
# text = '<title>hello</title>'
if match := re.search(pattern, text, re.IGNORECASE):
title = match.group(1)
# hello
CSS:
.container {
position: relative;
width: 500px;
}
.container div {
height: 300px;
}
.column-left {
width: 33%;
left: 0;
background: #00F;
position: absolute;
}
.column-center {
width: 34%;
background: #933;
margin-left: 33%;
position: absolute;
}
.column-right {
width: 33%;
right: 0;
position: absolute;
background: #999;
}
HTML:
<div class="container">
<div class="column-center">Column center</div>
<div class="column-left">Column left</div>
<div class="column-right">Column right</div>
</div>
Here is the Demo : http://jsfiddle.net/nyitsol/f0dv3q3z/
I just use Number()
:
var i=2;
var j=3;
var k = Number(i) + Number(j); // 5
I find that there are 3 package-based solutions to solve the problem. They are pyenchant, wordnet and corpus(self-defined or from ntlk). Pyenchant couldn't installed easily in win64 with py3. Wordnet doesn't work very well because it's corpus isn't complete. So for me, I choose the solution answered by @Sadik, and use 'set(words.words())' to speed up.
First:
pip3 install nltk
python3
import nltk
nltk.download('words')
Then:
from nltk.corpus import words
setofwords = set(words.words())
print("hello" in setofwords)
>>True
byte[] fileData = null;
using (var binaryReader = new BinaryReader(Request.Files[0].InputStream))
{
fileData = binaryReader.ReadBytes(Request.Files[0].ContentLength);
}
ImageConverter imageConverter = new System.Drawing.ImageConverter();
System.Drawing.Image image = imageConverter.ConvertFrom(fileData) as System.Drawing.Image;
image.Save(imageFullPath, System.Drawing.Imaging.ImageFormat.Jpeg);
Some things before the actual code..
the hash (#) you use as the selector is for IDs and not for names of elements. also the disabled attribute is not a true false scenario .. if it has disabled attribute it means that it is true .. you need to remove the attribute and not set it to false. Also there are the form selectors that identify specific types of items in a form ..
so the code would be
$("input:checkbox[name='chk0']").removeAttr('disabled');
Bringing the answer up-to-date
You should use the .prop()
method (added since v1.6)
$("input:checkbox[name='chk0']").prop('disabled', false); // to enable the checkbox
and
$("input:checkbox[name='chk0']").prop('disabled', true); // to disable the checkbox
I would suggest looking at how browsers handle forms by default. For example take a look at the form element <select multiple>
and how it handles multiple values from this example at w3schools.
<form action="/action_page.php">
<select name="cars" multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<input type="submit">
</form>
For PHP use:
<select name="cars[]" multiple>
Live example from above at w3schools.com
From above if you click "saab, opel" and click submit, it will generate a result of cars=saab&cars=opel. Then depending on the back-end server, the parameter cars should come across as an array that you can further process.
Hope this helps anyone looking for a more 'standard' way of handling this issue.
Use scipy:
import scipy;
a=[1,2,4];
print(scipy.mean(a));
A char
is an integral type. When you write
char ch = 'A';
you're setting the value of ch
to whatever number your compiler uses to represent the character 'A'
. That's usually the ASCII code for 'A'
these days, but that's not required. You're almost certainly using a system that uses ASCII.
Like any numeric type, you can initialize it with an ordinary number:
char ch = 13;
If you want do do arithmetic on a char
value, just do it: ch = ch + 1;
etc.
However, in order to display the value you have to get around the assumption in the iostreams library that you want to display char
values as characters rather than numbers. There are a couple of ways to do that.
std::cout << +ch << '\n';
std::cout << int(ch) << '\n'
FolderBrowserDialog fbd = new FolderBrowserDialog();
DialogResult result = fbd.ShowDialog();
string[] files = Directory.GetFiles(fbd.SelectedPath);
string[] dirs = Directory.GetDirectories(fbd.SelectedPath);
foreach (string item2 in dirs)
{
FileInfo f = new FileInfo(item2);
listBox1.Items.Add(f.Name);
}
foreach (string item in files)
{
FileInfo f = new FileInfo(item);
listBox1.Items.Add(f.Name);
}
You can also use the toBase64Image() method setting animation: false
var options = {
bezierCurve : false,
animation: false
};
If you are only looking to point to a different location for you identity file, the you can modify your ~/.ssh/config file with the following entry:
IdentityFile ~/.foo/identity
man ssh_config
to find other config options.
For me, there was no space left on your device.
In a regular expression, you can "capture" parts of the matched string with (brackets)
; in this case, you are capturing the (^|_)
and ([a-z])
parts of the match. These are numbered starting at 1, so you have back-references 1 and 2. Match 0 is the whole matched string.
The /e
modifier takes a replacement string, and substitutes backslash followed by a number (e.g. \1
) with the appropriate back-reference - but because you're inside a string, you need to escape the backslash, so you get '\\1'
. It then (effectively) runs eval
to run the resulting string as though it was PHP code (which is why it's being deprecated, because it's easy to use eval
in an insecure way).
The preg_replace_callback
function instead takes a callback function and passes it an array containing the matched back-references. So where you would have written '\\1'
, you instead access element 1 of that parameter - e.g. if you have an anonymous function of the form function($matches) { ... }
, the first back-reference is $matches[1]
inside that function.
So a /e
argument of
'do_stuff(\\1) . "and" . do_stuff(\\2)'
could become a callback of
function($m) { return do_stuff($m[1]) . "and" . do_stuff($m[2]); }
Or in your case
'strtoupper("\\2")'
could become
function($m) { return strtoupper($m[2]); }
Note that $m
and $matches
are not magic names, they're just the parameter name I gave when declaring my callback functions. Also, you don't have to pass an anonymous function, it could be a function name as a string, or something of the form array($object, $method)
, as with any callback in PHP, e.g.
function stuffy_callback($things) {
return do_stuff($things[1]) . "and" . do_stuff($things[2]);
}
$foo = preg_replace_callback('/([a-z]+) and ([a-z]+)/', 'stuffy_callback', 'fish and chips');
As with any function, you can't access variables outside your callback (from the surrounding scope) by default. When using an anonymous function, you can use the use
keyword to import the variables you need to access, as discussed in the PHP manual. e.g. if the old argument was
'do_stuff(\\1, $foo)'
then the new callback might look like
function($m) use ($foo) { return do_stuff($m[1], $foo); }
preg_replace_callback
is instead of the /e
modifier on the regex, so you need to remove that flag from your "pattern" argument. So a pattern like /blah(.*)blah/mei
would become /blah(.*)blah/mi
./e
modifier used a variant of addslashes()
internally on the arguments, so some replacements used stripslashes()
to remove it; in most cases, you probably want to remove the call to stripslashes
from your new callback.Another approach that's a little more semantic is to have a UL defined as your total 6 image width, each LI defined as float left and width defined - so that when LI #7 hits, it runs into the boundry of the UL, and is pushed down to the new row. You'll still have an open float that you'll want to clear after the /UL - but that can be done on the next element of the page, or as a clear div. Here's sort of the idea, you may have to mess with actual values, but this should give you the idea. The code is a little cleaner.
<style type="text/css">
ul#imageSet { width: 600px; margin: 0; padding:0; }
ul#imageSet li { float: left; width: 100px; height: 188px; margin: 0; padding:0; position: relative; list-style-type: none; }
.cornerimage { position: absolute; bottom: 0; right: 0; }
h3.nextelement { clear: both; }
</style>
<ul id="imageSet">
<li>
<img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
<img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
</li>
<li>
<img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
<img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
</li>
<li>
<img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
<img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
</li>
<li>
<img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
<img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
</li>
<li>
<img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
<img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
</li>
<li>
<img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
<img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
</li>
<li>
<img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
<img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
</li>
<li>
<img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
<img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
</li>
</ul>
<h3 class="nextelement">Next Element in Doc</h3>
You should use .Load
and not .LoadXML
"The LoadXml method is for loading an XML string directly. You want to use the Load method instead."
ref : Link
Updating the 'phones' function in Justen's answer using AngularJS 1.1.5 syntax.
Original:
phones: function($q, Phone) {
var deferred = $q.defer();
Phone.query(function(phones) {
deferred.resolve(phones);
});
return deferred.promise;
}
Updated:
phones: function(Phone) {
return Phone.query().$promise;
}
Much shorter thanks to the Angular team and contributors. :)
This is also the answer of Maximilian Hoffmann. Apparently that commit made it into 1.1.5.
You should probably use SQL_Latin1_General_Cp1_CI_AS_KI_WI
as your collation. The one you specify in your question is explictly case sensitive.
You can see a list of collations here.
.columnify {
display: flex;
> * {
flex: 1;
&:not(:first-child) {
margin-left: 2rem;
}
}
}
.columnify {_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
.columnify > * {_x000D_
flex: 1;_x000D_
}_x000D_
_x000D_
.columnify > *:not(:first-child) {_x000D_
margin-left: 2rem;_x000D_
}
_x000D_
<div class="columnify">_x000D_
<div style="display: inline-block; height: 20px; background-color: blue;"></div>_x000D_
<div style="display: inline-block; height: 20px; background-color: blue"></div>_x000D_
<div style="display: inline-block; height: 20px; background-color: blue"></div>_x000D_
</div>
_x000D_
Play with it on JSFiddle.
MySQL recommends using indexes for a variety of reasons including elimination of rows between conditions: http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html
This makes your datetime column an excellent candidate for an index if you are going to be using it in conditions frequently in queries. If your only condition is BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 30 DAY)
and you have no other index in the condition, MySQL will have to do a full table scan on every query. I'm not sure how many rows are generated in 30 days, but as long as it's less than about 1/3 of the total rows it will be more efficient to use an index on the column.
Your question about creating an efficient database is very broad. I'd say to just make sure that it's normalized and all appropriate columns are indexed (i.e. ones used in joins and where clauses).
I use these in my web projects, mainly with MVC. I have a handful of these written for the ViewData and TempData
/// <summary>
/// Checks the Request.QueryString for the specified value and returns it, if none
/// is found then the default value is returned instead
/// </summary>
public static T QueryValue<T>(this HtmlHelper helper, string param, T defaultValue) {
object value = HttpContext.Current.Request.QueryString[param] as object;
if (value == null) { return defaultValue; }
try {
return (T)Convert.ChangeType(value, typeof(T));
} catch (Exception) {
return defaultValue;
}
}
That way I can write something like...
<% if (Html.QueryValue("login", false)) { %>
<div>Welcome Back!</div>
<% } else { %>
<%-- Render the control or something --%>
<% } %>
I know that this is the wrong time to be answering this question but i just thought of something
i know it might be stressful but atleast it might still work
Now the trick is to create a lot of server side encoding scripts, they have to be decodable(for example a script that replaces all vowels with numbers and add the letter 'a' to every consonant so that the word 'bat' becomes ba1ta) then create a script that will randomize between the encoding scripts and create a cookie with the name of the encoding script being used (quick tip: try not to use the actual name of the encoding script for the cookie for example if our cookie is name 'encoding_script_being_used' and the randomizing script chooses an encoding script named MD10 try not to use MD10 as the value of the cookie but 'encoding_script4567656' just to prevent guessing) then after the cookie has been created another script will check for the cookie named 'encoding_script_being_used' and get the value, then it will determine what encoding script is being used.
Now the reason for randomizing between the encoding scripts was that the server side language will randomize which script to use to decode your javascript.js and then create a session or cookie to know which encoding scripts was used then the server side language will also encode your javascript .js and put it as a cookie
so people can't steal your code
but i would not advise this because
Vincent Povirk's answer won't work completely;
import zipfile
archive = zipfile.ZipFile('images.zip', 'r')
imgfile = archive.open('img_01.png')
...
You have to change it in:
import zipfile
archive = zipfile.ZipFile('images.zip', 'r')
imgdata = archive.read('img_01.png')
...
For details read the ZipFile
docs here.
Sorting NSMutableArray
is very simple:
NSMutableArray *arrayToFilter =
[[NSMutableArray arrayWithObjects:@"Photoshop",
@"Flex",
@"AIR",
@"Flash",
@"Acrobat", nil] autorelease];
NSMutableArray *productsToRemove = [[NSMutableArray array] autorelease];
for (NSString *products in arrayToFilter) {
if (fliterText &&
[products rangeOfString:fliterText
options:NSLiteralSearch|NSCaseInsensitiveSearch].length == 0)
[productsToRemove addObject:products];
}
[arrayToFilter removeObjectsInArray:productsToRemove];
The accepted answer on this question doesn't seem to work for me. I achieved the same thing with a slightly different method:
IF (select object_id from sys.foreign_keys where [name] = 'FK_TableName_TableName2') IS NOT NULL
BEGIN
ALTER TABLE dbo.TableName DROP CONSTRAINT FK_TableName_TableName2
END
use:
<input type="image" src=".."/>
or:
<button type="send"><img src=".."/> + any html code</button>
plus some CSS
The first problem is that your query string is wrong:
I think this: "INSERT INTO employee(hans,germany) values(?,?)"
should be like this: "INSERT INTO employee(name,country) values(?,?)"
The other problem is that you have a parameterized PreparedStatement and you don't set the parameters before running it.
You should add these to your code:
String inserting = "INSERT INTO employee(name,country) values(?,?)";
System.out.println("insert " + inserting);//
PreparedStatement ps = con.prepareStatement(inserting);
ps.setString(1,"hans"); // <----- this
ps.setString(2,"germany");// <---- and this
ps.executeUpdate();
void Keep()
Calling this method with in the current action ensures that all the items in TempData are not removed at the end of the current request.
@model MyProject.Models.EmpModel;
@{
Layout = "~/Views/Shared/_Layout.cshtml";
ViewBag.Title = "About";
var tempDataEmployeet = TempData["emp"] as Employee; //need typcasting
TempData.Keep(); // retains all strings values
}
void Keep(string key)
Calling this method with in the current action ensures that specific item in TempData is not removed at the end of the current request.
@model MyProject.Models.EmpModel;
@{
Layout = "~/Views/Shared/_Layout.cshtml";
ViewBag.Title = "About";
var tempDataEmployeet = TempData["emp"] as Employee; //need typcasting
TempData.Keep("emp"); // retains only "emp" string values
}
On OS X nothing helps poor builtin sed to become adequate. The solution is:
brew install gnu-sed
And then use gsed instead of sed, which will just work as expected.
I've encountered this problem with a input[type="datetime-local"]
, which is similar to this problem.
And I've found a way to overcome this kind of problems.
First, you must turn on chrome's shadow-root feature by "DevTools -> Settings -> General -> Elements -> Show user agent shadow DOM"
Then you can see all shadowed DOM elements, for example, for <input type="number">
, the full element with shadowed DOM is:
<input type="number">_x000D_
<div id="text-field-container" pseudo="-webkit-textfield-decoration-container">_x000D_
<div id="editing-view-port">_x000D_
<div id="inner-editor"></div>_x000D_
</div>_x000D_
<div pseudo="-webkit-inner-spin-button" id="spin"></div>_x000D_
</div>_x000D_
</input>
_x000D_
And according to these info, you can draft some CSS to hide unwanted elements, just as @Josh said.
You need to write code in the OnLocationChanged method, because this method is called when the location has changed. I.e. you need to save the new location to return it if getLocation is called.
If you don't use the onLocationChanged it always will be the old location.
The following script catenates several (relative/absolute) paths (BASEPATH) with a relative path (SUBDIR):
shopt -s extglob
SUBDIR="subdir"
for BASEPATH in '' / base base/ base// /base /base/ /base//; do
echo "BASEPATH = \"$BASEPATH\" --> ${BASEPATH%%+(/)}${BASEPATH:+/}$SUBDIR"
done
The output of which is:
BASEPATH = "" --> subdir
BASEPATH = "/" --> /subdir
BASEPATH = "base" --> base/subdir
BASEPATH = "base/" --> base/subdir
BASEPATH = "base//" --> base/subdir
BASEPATH = "/base" --> /base/subdir
BASEPATH = "/base/" --> /base/subdir
BASEPATH = "/base//" --> /base/subdir
The shopt -s extglob
is only necessary to allow BASEPATH to end on multiple slashes (which is probably nonsense). Without extended globing you can just use:
echo ${BASEPATH%%/}${BASEPATH:+/}$SUBDIR
which would result in the less neat but still working:
BASEPATH = "" --> subdir
BASEPATH = "/" --> /subdir
BASEPATH = "base" --> base/subdir
BASEPATH = "base/" --> base/subdir
BASEPATH = "base//" --> base//subdir
BASEPATH = "/base" --> /base/subdir
BASEPATH = "/base/" --> /base/subdir
BASEPATH = "/base//" --> /base//subdir
<div style="position: relative; width:600px;">_x000D_
<p>Content of unknown length</p>_x000D_
<div>Content of unknown height</div>_x000D_
<div id="spacer" style="width: 200px; height: 100px; float:left; display:inline-block"></div>_x000D_
<div class="btn" style="position: absolute; right: 0; bottom: 0; width: 200px; height: 100px;"></div>_x000D_
</div>
_x000D_
This should be a comment but I don't have enough reputation yet. The solution works, but visual studio code told me the following putting it into a css sheet:
inline-block is ignored due to the float. If 'float' has a value other than 'none', the box is floated and 'display' is treated as 'block'
So I did it like this
.spacer {
float: left;
height: 20px;
width: 200px;
}
And it works just as well.
int PIC_WIDTH= webView.getRight()-webView.getLeft();
I know this was answered a long time ago, but I've recently spent hours trying to solve a similar problem. The setup is local PC running Debian 8 using Eclipse CDT Neon.2, remote ARM7 board (Olimex) running Debian 7. Tool chain is Linaro 4.9 using gdbserver on the remote board and the Linaro GDB on the local PC. My issue was that the debug session would start and the program would execute, but breakpoints did not work and when manually paused "no source could be found" would result. My compile line options (Linaro gcc) included -ggdb -O0 as many have suggested but still the same problem. Ultimately I tried gdb proper on the remote board and it complained of no symbols. The curious thing was that 'file' reported debug not stripped on the target executable.
I ultimately solved the problem by adding -g to the linker options. I won't claim to fully understand why this helped, but I wanted to pass this on for others just in case it helps. In this case Linux did indeed need -g on the linker options.
if you do not want to use the collections library, you can always do something like this:
given that a
and b
are your lists, the following returns the number of matching elements (it considers the order).
sum([1 for i,j in zip(a,b) if i==j])
Therefore,
len(a)==len(b) and len(a)==sum([1 for i,j in zip(a,b) if i==j])
will be True
if both lists are the same, contain the same elements and in the same order. False
otherwise.
So, you can define the compare function like the first response above,but without the collections library.
compare = lambda a,b: len(a)==len(b) and len(a)==sum([1 for i,j in zip(a,b) if i==j])
and
>>> compare([1,2,3], [1,2,3,3])
False
>>> compare([1,2,3], [1,2,3])
True
>>> compare([1,2,3], [1,2,4])
False